如何在 shell 脚本中测量持续时间(以秒为单位)?
我想知道 Linux shell 脚本中一个操作需要多长时间。我该怎么做?
I wish to find out how long an operation takes in a Linux shell script. How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
正如其他人所建议的那样,使用 time 命令是一个好主意。
另一种选择是使用神奇的内置变量 $SECONDS,它包含自脚本开始执行以来的秒数。您可以说:
我认为这是特定于 bash 的,但由于您使用的是 Linux,所以我假设您正在使用 bash。
Using the time command, as others have suggested, is a good idea.
Another option is to use the magic built-in variable $SECONDS, which contains the number of seconds since the script started executing. You can say:
I think this is bash-specific, but since you're on Linux, I assume you're using bash.
使用
时间
命令。时间 ls /bin
。Use the
time
command.time ls /bin
.尝试以下示例:
Try following example:
许多答案都提到
$SECONDS
,但该变量实际上是 比他们意识到的还要好:这意味着您可以直接在脚本末尾直接查询该变量来打印经过的时间:
您还可以为较小的部分计时,如下所示:
Many of the answers mention
$SECONDS
, but that variable is actually even better than they realize:This means you can simply query this variable directly at the end of your script to print the elapsed time:
You can also time smaller sections like so:
这是查找经过的时间(以毫秒为单位)的脚本。将 sleep 60 行替换为您要执行的代码。
Here is the script to find the time elapsed in milliseconds. Replace the sleep 60 line with the code you want to execute.
GNU
time
我也对 GNU
time
命令非常感兴趣:https://www.gnu.org/software/time/ 与 Bash 内置的time
相比,它提供了一些重要的选项 -在。示例用法:
输出:
解释:
env
:查找/usr/bin/time
而不是 Bash 内置的--format '%e'
:以秒为单位打印时间,请参阅人工时间
。这通常是我在基准测试时想要的:单个数字而不是分钟 + 秒。
我经常使用的一个重要模式是:
GitHub 上游 。
输出:
说明:
--output
:将时间输出到文件。默认情况下,输出会发送到 stderr,因此此选项对于将时间与命令的 stderr 分开非常重要。
--append
:附加到文件而不是覆盖。这使我可以将整个基准测试输出集中在一个文件中。
GNU
time
I'm also a big fun of the GNU
time
command: https://www.gnu.org/software/time/ which offers some important options compared to thetime
Bash built-in.Sample usage:
Output:
Explanation:
env
: to find/usr/bin/time
instead of the Bash built-in--format '%e'
: print time in seconds, seeman time
.This is often what I want when benchmarking: a single number rather than minutes + seconds.
And an important pattern I often use is:
GitHub upstream.
Output:
Explanation:
--output
: output the time to a file.By default, the output goes to stderr, so this option is important to separate the timing from the stderr of the command.
--append
: append to the file instead of overwriting.This allows me to concentrate the entire benchmark output in a single file.