我想在一些不同的条件下在linux shell中执行一些东西,并且能够输出每次执行的执行时间。
我知道我可以写一个perl或python脚本,可以做到这一点,但有一种方法我可以在shell中做到这一点吗?(恰好是bash)
我想在一些不同的条件下在linux shell中执行一些东西,并且能够输出每次执行的执行时间。
我知道我可以写一个perl或python脚本,可以做到这一点,但有一种方法我可以在shell中做到这一点吗?(恰好是bash)
当前回答
一个可能简单的方法(可能不能满足不同用户的需求)是使用shell PROMPT。这是一个简单的解决方案,在某些情况下可能有用。你可以使用bash提示功能,如下例所示:
export PS1='[\t \u@\h]\$'
上面的命令将导致shell提示符更改为:
[HH:MM:SS username@hostname]$
每次运行命令(或按回车键)返回到shell提示符时,提示符将显示当前时间。
notes: 1) beware that if you waited for sometime before you type your next command, then this time need to be considered, i.e the time displayed in the shell prompt is the timestamp when the shell prompt was displayed, not when you enter command. some users choose to hit Enter key to get a new prompt with a new timestamp before they are ready for the next command. 2) There are other available options and modifiers that can be used to change the bash prompt, refer to ( man bash ) for more details.
其他回答
使用内置的time关键字:
$ help time time: time [-p] PIPELINE Execute PIPELINE and print a summary of the real time, user CPU time, and system CPU time spent executing PIPELINE when it terminates. The return status is the return status of PIPELINE. The `-p' option prints the timing summary in a slightly different format. This uses the value of the TIMEFORMAT variable as the output format.
例子:
$ time sleep 2
real 0m2.009s user 0m0.000s sys 0m0.004s
如果您打算以后使用时间来计算,请学习如何使用/usr/bin/time的-f选项来输出节省时间的代码。下面是我最近使用的一些代码,用于获取和排序整个班级的学生程序的执行时间:
fmt="run { date = '$(date)', user = '$who', test = '$test', host = '$(hostname)', times = { user = %U, system = %S, elapsed = %e } }"
/usr/bin/time -f "$fmt" -o $timefile command args...
后来我将所有$timefile文件连接起来,并将输出输出到Lua解释器中。你可以用Python或bash或任何你喜欢的语法做同样的事情。我喜欢这个技巧。
一个可能简单的方法(可能不能满足不同用户的需求)是使用shell PROMPT。这是一个简单的解决方案,在某些情况下可能有用。你可以使用bash提示功能,如下例所示:
export PS1='[\t \u@\h]\$'
上面的命令将导致shell提示符更改为:
[HH:MM:SS username@hostname]$
每次运行命令(或按回车键)返回到shell提示符时,提示符将显示当前时间。
notes: 1) beware that if you waited for sometime before you type your next command, then this time need to be considered, i.e the time displayed in the shell prompt is the timestamp when the shell prompt was displayed, not when you enter command. some users choose to hit Enter key to get a new prompt with a new timestamp before they are ready for the next command. 2) There are other available options and modifiers that can be used to change the bash prompt, refer to ( man bash ) for more details.
你可以使用time和subshell ():
time (
for (( i=1; i<10000; i++ )); do
echo 1 >/dev/null
done
)
或者在同一个shell{}中:
time {
for (( i=1; i<10000; i++ )); do
echo 1 >/dev/null
done
}
#!/bin/bash
START=$(date +%s)
# do something
# start your script work here
ls -R /etc > /tmp/x
rm -f /tmp/x
# your logic ends here
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "It took $DIFF seconds"