Bash:计算脚本运行所需的时间

时间:2016-06-08 07:21:47

标签: bash

有没有办法让bash脚本打印运行多长时间?

非常简单的事情:

#!/bin/bash
something to start time
command to be run
something to calculate runtime and print result

3 个答案:

答案 0 :(得分:3)

有标准工具time

剧本:

#!/bin/bash

echo start
sleep 2
echo end

用法:

$ time ./so.sh       
start
end
./so.sh  0.00s user 0.01s system 0% cpu 2.007 total

答案 1 :(得分:2)

您可以使用time命令:

  

时间运行程序并总结系统资源使用

例如:

time <command>

将为您提供命令的执行时间

答案 2 :(得分:0)

正如其他答案中所写 - 时间对整个剧本来说是最好的。

另一方面,如果你想只计算部分脚本的长度,试着使用这段代码:

#!/bin/bash
T="$(date +%s)"

sleep 2

T="$(($(date +%s)-T))"
echo "It took ${T} seconds!"

这只需要一些日期

  自1970-01-01 00:00:00 UTC以来

秒(更多请参见man date

一个在执行之前,一个在另一个之后减去一个。

您可以稍微试验一下以获得更高的准确度。

相关问题