gpt4 book ai didi

bash - 使用 Bash 计算程序的平均执行时间

转载 作者:行者123 更新时间:2023-11-29 09:04:02 24 4
gpt4 key购买 nike

要获取任何可执行文件的执行时间,例如 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)
}'
}

例子:

avg_time 5 sleep 1

给你

real 1.000000
user 0.000000
sys 0.000000

这可以很容易地增强为:

  • 在两次执行之间休眠一段给定的时间
  • 在执行之间随机休眠一段时间(在一定范围内)

来自man timetime -p的含义:

   -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.

您可能还想看看这个命令行基准测试工具:

sharkdp/hyperfine

关于bash - 使用 Bash 计算程序的平均执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54920113/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com