我是bash脚本的新手。如何执行以下命令以捕获执行命令的时间。
我在数组变量中捕获了我的交易。然后,我正在完成交易……
你可以用 date +%s 在操作之前和之后找到以秒为单位的时差。例如 :
date +%s
array=( 5 10 15 20 25 ) for val in "${array[@]}" do starttime=$(date +%s) sleep "$val" # sleeping for '$val' seconds in each iteration #you should replace the above with the actual process. endtime=$(date +%s) echo "Time taken for the process is $((endtime-starttime))s" done
这会给
Time taken for the process is 5s Time taken for the process is 10s Time taken for the process is 15s Time taken for the process is 20s Time taken for the process is 25s
但是,我应该承认它可以提供几秒钟的精度。
该 +%s 格式字符串需要特别提及。该 date manpage说:
+%s
date
自1970-01-01 00:00:00 UTC以来的%s秒
本质上,我们只计算过去参考点的经过时间(以秒为单位),然后计算结束时间和开始时间之间的差异。一旦你有时间在几秒钟内,使用明确定义的数学隔离小时和分钟。
正如@ChalresDuffy指出的那样 这个 评论,你可以使用 $ SECONDS 内部变量来计算时差。也, $ EPOCHREALTIME 如果需要微秒级的粒度,可以使用。