moo*_*cow 5 bash time execution
为了获得任何可执行文件的执行时间,比方说a.out,我可以简单地写一下time ./a.out.这将输出实时,用户时间和系统时间.
是否有可能编写一个运行程序多次的bash脚本并计算并输出平均实际执行时间?
您可以编写一个循环并收集time命令的输出并将其传递awk给计算平均值:
avg_time() {
#
# usage: avg_time n command ...
#
n=$1; shift
(($# > 0)) || return # bail if no command given
for ((i = 0; i < n; i++)); do
{ time -p "$@" &>/dev/null; } 2>&1 # ignore the output of the command
# but collect time's output in stdout
done | awk '
/real/ { real = real + $2; nr++ }
/user/ { user = user + $2; nu++ }
/sys/ { sys = sys + $2; ns++}
END {
if (nr>0) printf("real %f\n", real/nr);
if (nu>0) printf("user %f\n", user/nu);
if (ns>0) printf("sys %f\n", sys/ns)
}'
}
Run Code Online (Sandbox Code Playgroud)
例:
avg_time 5 sleep 1
Run Code Online (Sandbox Code Playgroud)
会给你的
real 1.000000
user 0.000000
sys 0.000000
Run Code Online (Sandbox Code Playgroud)
这可以很容易地增强到:
time -p来自的含义man time:
Run Code Online (Sandbox Code Playgroud)-p When in the POSIX locale, use the precise traditional format "real %f\nuser %f\nsys %f\n" (with numbers in seconds) where the number of decimals in the output for %f is unspecified but is sufficient to express the clock tick accuracy, and at least one.
您可能还想查看此命令行基准测试工具: