使用 date 命令测量运行时间
发表于 2008年11月26日
当运行需要很长时间的 bash 脚本时,通常需要知道脚本的运行时间。 除了整体运行时间之外,了解脚本某些部分的运行时间通常也很有用。time命令实际上没有帮助,因为它旨在为单个命令计时,而不是为一系列命令计时。 通过使用date的 *%s* 格式,此处描述的脚本允许您根据需要创建任意数量的计时器,并对您想要的脚本的任何部分进行计时。
该date命令的 *%s* 格式输出自 Unix 时间开始以来的秒数
$ date +'%s' 1227068222
使用这两个值,您可以确定经过的时间。
以下脚本定义了一个 bash 函数timer。 如果在没有参数的情况下调用它,它将输出当前的秒数。 如果使用参数调用它,它会假定该参数是先前通过调用timer获得的,不带参数,并且它输出自获得第一个值以来经过的时间。
#!/bin/bash
#
# Elapsed time. Usage:
#
# t=$(timer)
# ... # do something
# printf 'Elapsed time: %s\n' $(timer $t)
# ===> Elapsed time: 0:01:12
#
#
#####################################################################
# If called with no arguments a new timer is returned.
# If called with arguments the first is used as a timer
# value and the elapsed time is returned in the form HH:MM:SS.
#
function timer()
{
if [[ $# -eq 0 ]]; then
echo $(date '+%s')
else
local stime=$1
etime=$(date '+%s')
if [[ -z "$stime" ]]; then stime=$etime; fi
dt=$((etime - stime))
ds=$((dt % 60))
dm=$(((dt / 60) % 60))
dh=$((dt / 3600))
printf '%d:%02d:%02d' $dh $dm $ds
fi
}
# If invoked directly run test code.
if [[ $(basename $0 .sh) == 'timer' ]]; then
t=$(timer)
read -p 'Enter when ready...' p
printf 'Elapsed time: %s\n' $(timer $t)
fi
## vim: tabstop=4: shiftwidth=4: noexpandtab:
## kate: tab-width 4; indent-width 4; replace-tabs false;
要使用该函数,首先以下列方式获取起始计时器值
tmr=$(timer)
然后,当您想知道经过了多少时间时,传递原始计时器值并打印结果。 例如,要打印上面获得的计时器
printf 'Elapsed time: %s\n' $(timer $tmr)
直接运行timer.sh脚本会以测试模式运行它。 它获取一个计时器,等待您按 Enter 键,然后打印经过的时间
$ sh timer.sh Enter when ready... # Wait a while here Elapsed time: 0:01:12