问题描述
我正在从一个脚本运行许多命令并测量执行时间(仅其中几个)。这我知道如何处理 time
。但我也想只在整个脚本完成后(在 shell 或文件中)输出所有时间。我该怎么做?
编辑: 抱歉,我应该指定我使用的是 Fish shell。(尽管如此,我会将 bash 添加到标签中,以便其他人可以使用答案。)
解决方法
#!/bin/bash
#
declare -a toutput
declare -a commands
#
stime()
{
start=`date +%s`
# run command
$1
end=`date +%s`
toutput+=("$1 : $((end-start)),")
}
# set array of commnds
commands+=("'ls -1 /var/log'")
commands+=("'sleep 3'")
commands+=("'sleep 5'")
echo "==================="
echo ${commands[@]}
echo "==================="
# execute commands and log times to toutput
#
for cc in "${commands[@]}"
do
stime "$(echo ${cc} | tr -d \')"
done
echo "times = (" ${toutput[@]} ")"
,
Bash 4.2 及更高版本有一个晦涩的命令用于将 unix 时间保存到变量中。
#!/bin/bash
# start time
printf -v s_time '%(%s)T' -1
# do stuff
sleep 1
sleep 2
sleep 3
# end time
printf -v e_time '%(%s)T' -1
# do more stuff
sleep 4
# print result
echo It took $(( e_time - s_time )) seconds
显示“do stuff”多个命令的运行时间
It took 6 seconds
,
选项 1:
尝试以这种方式运行您的脚本:
time ./your_script.sh
https://www.cyberciti.biz/faq/unix-linux-time-command-examples-usage-syntax/
选项 2:
npm install -g gnomon
./your_script.sh | gnomon