如何计算bash脚本中经过的时间?
我使用如何计算bash脚本中经过的时间?,bash,date,Bash,Date,我使用日期+“%T”打印开始和结束时间,结果如下: 10:33:56 10:36:10 2m 14s 如何计算和打印这两者之间的差异 我想得到如下信息: 10:33:56 10:36:10 2m 14s Bash有一个方便的SECONDSbuildin变量,跟踪自shell启动以来经过的秒数。此变量在分配给时保留其属性,分配后返回的值是自分配后的秒数加上分配的值 因此,您可以在启动定时事件之前将SECONDS设置为0,只需在事件之后读取SECONDS,并在显示之前执行时间算术 #!/us
日期+“%T”
打印开始和结束时间,结果如下:
10:33:56
10:36:10
2m 14s
如何计算和打印这两者之间的差异
我想得到如下信息:
10:33:56
10:36:10
2m 14s
Bash有一个方便的
SECONDS
buildin变量,跟踪自shell启动以来经过的秒数。此变量在分配给时保留其属性,分配后返回的值是自分配后的秒数加上分配的值
因此,您可以在启动定时事件之前将SECONDS
设置为0,只需在事件之后读取SECONDS
,并在显示之前执行时间算术
#!/usr/bin/env bash
SECONDS=0
# do some work
duration=$SECONDS
echo "$(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed."
由于此解决方案不依赖于date+%s
(这是GNU扩展),因此它可以移植到Bash支持的所有系统。以下是我的做法:
START=$(date +%s);
sleep 1; # Your stuff
END=$(date +%s);
echo $((END-START)) | awk '{print int($1/60)":"int($1%60)}'
非常简单,首先计算开始时的秒数,然后计算结束时的秒数,并以分钟为单位打印差值:秒。我想提出另一种避免调用
日期
命令的方法。如果您已经收集了%T
日期格式的时间戳,则可能会有所帮助:
ts_get_sec()
{
read -r h m s <<< $(echo $1 | tr ':' ' ' )
echo $(((h*60*60)+(m*60)+s))
}
start_ts=10:33:56
stop_ts=10:36:10
START=$(ts_get_sec $start_ts)
STOP=$(ts_get_sec $stop_ts)
DIFF=$((STOP-START))
echo "$((DIFF/60))m $((DIFF%60))s"
ts_get_sec()
{
从Daniel Kamil Kozar的回答中读取-r h m s,以显示小时/分/秒:
echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"
因此,完整的脚本应该是:
date1=$(date +"%s")
date2=$(date +"%s")
DIFF=$(($date2-$date1))
echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"
这里有一些魔力:
time1=14:30
time2=$( date +%H:%M ) # 16:00
diff=$( echo "$time2 - $time1" | sed 's%:%+(1/60)*%g' | bc -l )
echo $diff hours
# outputs 1.5 hours
sed
将:
替换为转换为1/60的公式。然后由bc
截止日期(GNU coreutils)7.4进行的时间计算现在可以使用-d进行算术:
$ date -d -30days
Sat Jun 28 13:36:35 UTC 2014
$ date -d tomorrow
Tue Jul 29 13:40:55 UTC 2014
您可以使用的单位是天、年、月、小时、分钟和秒:
$ date -d tomorrow+2days-10minutes
Thu Jul 31 13:33:02 UTC 2014
或者把它包起来一点
alias timerstart='starttime=$(date +"%s")'
alias timerstop='echo seconds=$(($(date +"%s")-$starttime))'
这样就行了
timerstart; sleep 2; timerstop
seconds=2
我意识到这是一篇较老的文章,但我今天在编写一个脚本时遇到了它,该脚本将从日志文件中提取日期和时间,并计算增量。下面的脚本肯定有些过分,我强烈建议检查我的逻辑和数学
#!/bin/bash
dTime=""
tmp=""
#firstEntry="$(head -n 1 "$LOG" | sed 's/.*] \([0-9: -]\+\).*/\1/')"
firstEntry="2013-01-16 01:56:37"
#lastEntry="$(tac "$LOG" | head -n 1 | sed 's/.*] \([0-9: -]\+\).*/\1/')"
lastEntry="2014-09-17 18:24:02"
# I like to make the variables easier to parse
firstEntry="${firstEntry//-/ }"
lastEntry="${lastEntry//-/ }"
firstEntry="${firstEntry//:/ }"
lastEntry="${lastEntry//:/ }"
# remove the following lines in production
echo "$lastEntry"
echo "$firstEntry"
# compute days in last entry
for i in `seq 1 $(echo $lastEntry|awk '{print $2}')`; do {
case "$i" in
1|3|5|7|8|10|12 )
dTime=$(($dTime+31))
;;
4|6|9|11 )
dTime=$(($dTime+30))
;;
2 )
dTime=$(($dTime+28))
;;
esac
} done
# do leap year calculations for all years between first and last entry
for i in `seq $(echo $firstEntry|awk '{print $1}') $(echo $lastEntry|awk '{print $1}')`; do {
if [ $(($i%4)) -eq 0 ] && [ $(($i%100)) -eq 0 ] && [ $(($i%400)) -eq 0 ]; then {
if [ "$i" = "$(echo $firstEntry|awk '{print $1}')" ] && [ $(echo $firstEntry|awk '{print $2}') -lt 2 ]; then {
dTime=$(($dTime+1))
} elif [ $(echo $firstEntry|awk '{print $2}') -eq 2 ] && [ $(echo $firstEntry|awk '{print $3}') -lt 29 ]; then {
dTime=$(($dTime+1))
} fi
} elif [ $(($i%4)) -eq 0 ] && [ $(($i%100)) -ne 0 ]; then {
if [ "$i" = "$(echo $lastEntry|awk '{print $1}')" ] && [ $(echo $lastEntry|awk '{print $2}') -gt 2 ]; then {
dTime=$(($dTime+1))
} elif [ $(echo $lastEntry|awk '{print $2}') -eq 2 ] && [ $(echo $lastEntry|awk '{print $3}') -ne 29 ]; then {
dTime=$(($dTime+1))
} fi
} fi
} done
# substract days in first entry
for i in `seq 1 $(echo $firstEntry|awk '{print $2}')`; do {
case "$i" in
1|3|5|7|8|10|12 )
dTime=$(($dTime-31))
;;
4|6|9|11 )
dTime=$(($dTime-30))
;;
2 )
dTime=$(($dTime-28))
;;
esac
} done
dTime=$(($dTime+$(echo $lastEntry|awk '{print $3}')-$(echo $firstEntry|awk '{print $3}')))
# The above gives number of days for sample. Now we need hours, minutes, and seconds
# As a bit of hackery I just put the stuff in the best order for use in a for loop
dTime="$(($(echo $lastEntry|awk '{print $6}')-$(echo $firstEntry|awk '{print $6}'))) $(($(echo $lastEntry|awk '{print $5}')-$(echo $firstEntry|awk '{print $5}'))) $(($(echo $lastEntry|awk '{print $4}')-$(echo $firstEntry|awk '{print $4}'))) $dTime"
tmp=1
for i in $dTime; do {
if [ $i -lt 0 ]; then {
case "$tmp" in
1 )
tmp="$(($(echo $dTime|awk '{print $1}')+60)) $(($(echo $dTime|awk '{print $2}')-1))"
dTime="$tmp $(echo $dTime|awk '{print $3" "$4}')"
tmp=1
;;
2 )
tmp="$(($(echo $dTime|awk '{print $2}')+60)) $(($(echo $dTime|awk '{print $3}')-1))"
dTime="$(echo $dTime|awk '{print $1}') $tmp $(echo $dTime|awk '{print $4}')"
tmp=2
;;
3 )
tmp="$(($(echo $dTime|awk '{print $3}')+24)) $(($(echo $dTime|awk '{print $4}')-1))"
dTime="$(echo $dTime|awk '{print $1" "$2}') $tmp"
tmp=3
;;
esac
} fi
tmp=$(($tmp+1))
} done
echo "The sample time is $(echo $dTime|awk '{print $4}') days, $(echo $dTime|awk '{print $3}') hours, $(echo $dTime|awk '{print $2}') minutes, and $(echo $dTime|awk '{print $1}') seconds."
您将得到如下输出
2012 10 16 01 56 37
2014 09 17 18 24 02
The sample time is 700 days, 16 hours, 27 minutes, and 25 seconds.
我对脚本进行了一点修改,使其独立(即只设置变量值),但可能也会出现一般的想法。您可能需要一些额外的负值错误检查。Seconds
要测量经过的时间(以秒为单位),我们需要:
- 表示已用秒数和秒数的整数
- 将此类整数转换为可用格式的方法
已用秒数的整数值:
- 有两种bash内部方法可以查找已用秒数的整数值:
- Bash变量SECONDS(如果SECONDS未设置,它将丢失其特殊属性)
- 将秒的值设置为0:
SECONDS=0
sleep 1 # Process to execute
elapsedseconds=$SECONDS
- 在开始时存储变量
秒的值
:
a=$SECONDS
sleep 1 # Process to execute
elapsedseconds=$(( SECONDS - a ))
- Bash printf选项
%(datefmt)T
:
将此类整数转换为可用格式
bash internalprintf
可以直接执行以下操作:
$ TZ=UTC0 printf '%(%H:%M:%S)T\n' 12345
03:25:45
date -D "%H:%M:%S" -d "10:33:56" +"%Y.%m.%d-%H:%M:%S"
同样地
$ elapsedseconds=$((12*60+34))
$ TZ=UTC0 printf '%(%H:%M:%S)T\n' "$elapsedseconds"
00:12:34
但这将在超过24小时的持续时间内失败,因为我们实际上打印的是挂钟时间,而不是真正的持续时间:
$ hours=30;mins=12;secs=24
$ elapsedseconds=$(( ((($hours*60)+$mins)*60)+$secs ))
$ TZ=UTC0 printf '%(%H:%M:%S)T\n' "$elapsedseconds"
06:12:24
对于细节爱好者,来自:
%(FORMAT)T
输出使用FORMAT生成的日期时间字符串
作为的格式字符串。关联的参数是
之后的秒数,或-1(当前时间)或-2(外壳
启动时间)。如果未提供相应的参数,则当前
时间用作默认值
因此,您可能只需调用textifyDuration$elpasedseconds
,其中textifyDuration
是持续时间打印的另一个实现:
textifyDuration() {
local duration=$1
local shiff=$duration
local secs=$((shiff % 60)); shiff=$((shiff / 60));
local mins=$((shiff % 60)); shiff=$((shiff / 60));
local hours=$shiff
local splur; if [ $secs -eq 1 ]; then splur=''; else splur='s'; fi
local mplur; if [ $mins -eq 1 ]; then mplur=''; else mplur='s'; fi
local hplur; if [ $hours -eq 1 ]; then hplur=''; else hplur='s'; fi
if [[ $hours -gt 0 ]]; then
txt="$hours hour$hplur, $mins minute$mplur, $secs second$splur"
elif [[ $mins -gt 0 ]]; then
txt="$mins minute$mplur, $secs second$splur"
else
txt="$secs second$splur"
fi
echo "$txt (from $duration seconds)"
}
GNU日期。
要获得格式化的时间,我们应该以多种方式使用外部工具(GNU日期),使其长度达到近一年,包括纳秒
数学里面的日期。
不需要外部运算,在日期内一步完成所有运算:
date -u -d "0 $FinalDate seconds - $StartDate seconds" +"%H:%M:%S"
是的,命令字符串中有一个0
0。这是必需的
假设您可以将date+%T”
命令更改为date+%s”
命令,以便在几秒钟内存储(打印)值
请注意,该命令仅限于:
$StartDate
和$FinalDate
秒的正值
$FinalDate
中的值比$StartDate
大(时间较晚)
- 时间差小于24小时
- 您接受时、分、秒的输出格式。非常容易更改
- 可以使用-u UTC时间。以避免“DST”和本地时间修正
如果您必须使用10:33:56
字符串,那么只需将其转换为秒,
此外,秒可以缩写为秒:
string1="10:33:56"
string2="10:36:10"
StartDate=$(date -u -d "$string1" +"%s")
FinalDate=$(date -u -d "$string2" +"%s")
date -u -d "0 $FinalDate sec - $StartDate sec" +"%H:%M:%S"
请注意,秒时间转换(如上所示)是相对于“这一天”(今天)的开始
这个概念可以扩展到纳秒,如下所示:
string1="10:33:56.5400022"
string2="10:36:10.8800056"
StartDate=$(date -u -d "$string1" +"%s.%N")
FinalDate=$(date -u -d "$string2" +"%s.%N")
date -u -d "0 $FinalDate sec - $StartDate sec" +"%H:%M:%S.%N"
如果需要计算更长(最多364天)的时差,我们必须使用(某些)年的开始作为参考,并使用格式值%j
(年中的天数):
类似于:
string1="+10 days 10:33:56.5400022"
string2="+35 days 10:36:10.8800056"
StartDate=$(date -u -d "2000/1/1 $string1" +"%s.%N")
FinalDate=$(date -u -d "2000/1/1 $string2" +"%s.%N")
date -u -d "2000/1/1 $FinalDate sec - $StartDate sec" +"%j days %H:%M:%S.%N"
Output:
026 days 00:02:14.340003400
不幸的是,在这种情况下,我们需要手动从天数中减去1
1。
date命令将一年中的第一天视为1。
没那么难
a=( $(date -u -d "2000/1/1 $FinalDate sec - $StartDate sec" +"%j days %H:%M:%S.%N") )
a[0]=$((10#${a[0]}-1)); echo "${a[@]}"
使用长秒数是有效的,并记录在此处:
忙箱日期
小型设备中使用的工具(要安装的可执行文件非常小):Busybox
创建一个名为date的busybox链接:
$ ln -s /bin/busybox date
然后通过调用此date
(将其放在包含路径的目录中)来使用它
或者将别名设置为:
$ alias date='busybox date'
Busybox date有一个很好的选项:-D来接收输入时间的格式。
这打开了许多格式,可以作为时间使用。
使用-D选项
date -D "%H:%M:%S" -d "10:33:56" +"%Y.%m.%d-%H:%M:%S"
$ string1="10:33:56"
$ date -u -D "%Y.%m.%d-%H:%M:%S" -d "1970.01.01-$string1" +"%Y.%m.%d-%H:%M:%S"
1970.01.01-10:33:56
$ date -u -d "1970.01.01-$string1" +"%Y.%m.%d-%H:%M:%S"
1970.01.01-10:33:56
$ date -u -d "1970.01.01-$string1" +"%s"
52436
string1="10:33:56"
string2="10:36:10"
t1=$(date -u -d "1970.01.01-$string1" +"%s")
t2=$(date -u -d "1970.01.01-$string2" +"%s")
echo $(( t2 - t1 ))
$ date -u -D "%s" -d "$(( t2 - t1 ))" +"%H:%M:%S"
00:02:14
$ ./timediff.py 1:10:15 2:12:44
1:02:29
$ echo "diff is `./timediff.py 10:51.6 12:44` (in hh:mm:ss format)"
diff is 0:01:52.4 (in hh:mm:ss format)
$ ./timediff.py 120:0 200:0
1:20:0
$ ./timediff.py 0 3600
1:00:0
$ ./timediff.py 0 3.25:0:0
3:15:0
#!/usr/bin/python
import sys
def x60(h,m):
return 60*float(h)+float(m)
def seconds(time):
try:
h,m,s = time.split(':')
return x60(x60(h,m),s)
except ValueError:
try:
m,s = time.split(':')
return x60(m,s)
except ValueError:
return float(time)
def difftime(start, end):
d = seconds(end) - seconds(start)
print '%d:%02d:%s' % (d/3600,d/60%60,('%02f' % (d%60)).rstrip('0').rstrip('.'))
if __name__ == "__main__":
difftime(sys.argv[1],sys.argv[2])
$ units
2411 units, 71 prefixes, 33 nonlinear units
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: s
* 134
/ 0.0074626866
You have: (10hr+36min+10s)-(10hr+33min+56s)
You want: min
* 2.2333333
/ 0.44776119
function countTimeDiff() {
timeA=$1 # 09:59:35
timeB=$2 # 17:32:55
# feeding variables by using read and splitting with IFS
IFS=: read ah am as <<< "$timeA"
IFS=: read bh bm bs <<< "$timeB"
# Convert hours to minutes.
# The 10# is there to avoid errors with leading zeros
# by telling bash that we use base 10
secondsA=$((10#$ah*60*60 + 10#$am*60 + 10#$as))
secondsB=$((10#$bh*60*60 + 10#$bm*60 + 10#$bs))
DIFF_SEC=$((secondsB - secondsA))
echo "The difference is $DIFF_SEC seconds.";
SEC=$(($DIFF_SEC%60))
MIN=$((($DIFF_SEC-$SEC)%3600/60))
HRS=$((($DIFF_SEC-$MIN*60)/3600))
TIME_DIFF="$HRS:$MIN:$SEC";
echo $TIME_DIFF;
}
$ countTimeDiff 2:15:55 2:55:16
The difference is 2361 seconds.
0:39:21
date -ujf%s $(($(date -jf%T "10:36:10" +%s) - $(date -jf%T "10:33:56" +%s))) +%T
# 00:02:14
date -ujf%s $(($(date -jf%T "10:36:10" +%s) - $(date -jf%T "10:33:56" +%s))) \
+'%-Hh %-Mm %-Ss'
# 0h 2m 14s
date -ujf%s $(($(date -jf%T "10:36:10" +%s) - $(date -jf%T "10:33:56" +%s))) \
+'%-Hh %-Mm %-Ss' | sed "s/[[:<:]]0[hms] *//g"
# 2m 14s
#!/bin/bash
# save the current time
start_time=$( date +%s.%N )
# tested program
sleep 1
# the current time after the program has finished
# minus the time when we started, in seconds.nanoseconds
elapsed_time=$( date +%s.%N --date="$start_time seconds ago" )
echo elapsed_time: $elapsed_time
$ ./time_elapsed.sh
elapsed_time: 1.002257120
start=`date`
# <processing code>
stop=`date`
duration=`date -ud@$(($(date -ud"$stop" +%s)-$(date -ud"$start" +%s))) +%T`
echo $start
echo $stop
echo $duration
Wed Feb 7 12:31:16 CST 2018
Wed Feb 7 12:32:25 CST 2018
00:01:09
[root@test ~]# date1=$(date +"%s"); date
Wed Feb 21 23:00:20 MYT 2018
[root@test ~]#
[root@test ~]# date2=$(date +"%s"); date
Wed Feb 21 23:00:33 MYT 2018
[root@test ~]#
[root@test ~]# diff=$(($date2-$date1))
[root@test ~]#
[root@test ~]# echo "Duration: $(($DIFF / 3600 )) hours $((($DIFF % 3600) / 60)) minutes $(($DIFF % 60)) seconds"
-bash: / 3600 : syntax error: operand expected (error token is "/ 3600 ")
[root@test ~]#
[root@test ~]# echo "Duration: $(($diff / 3600 )) hours $((($diff % 3600) / 60)) minutes $(($diff % 60)) seconds"
Duration: 0 hours 0 minutes 13 seconds
[root@test ~]#
#!/bin/bash
START_TIME=$(date +%s)
sleep 4
echo "Total time elapsed: $(date -ud "@$(($(date +%s) - $START_TIME))" +%T) (HH:MM:SS)"
$ ./total_time_elapsed.sh
Total time elapsed: 00:00:04 (HH:MM:SS)
time::clock() {
[ -z "$ts" ]&&{ ts=`date +%s%N`;return;}||te=`date +%s%N`
printf "%6.4f" $(echo $((te-ts))/1000000000 | bc -l)
unset ts te
}
$ cat script.sh
# ... code ...
time::clock
sleep 0.5
echo "Total time: ${time::clock}"
# ... more code ...
$ ./script.sh
Total time: 0.5060