shell指令碼樣本:計算毫秒級、微秒級時間差,shell微秒
有時候需要計算命令的執行時間長度,可以使用time命令,雖然time命令可以精確到毫秒級,但time命令無法計算一堆命令的執行時間。可以也可以直接使用date命令計算命令執行前後的時間差,但直接使用date命令計算時間差只能精確到秒級。因此,要計算毫秒級或者微秒級的時間長度,需要對date命令的結果進行一番計算轉換。
本文只給出了毫秒級時間差的計算方法,若要計算微秒級時間差,對指令碼稍作修改即可。
指令碼如下:
#!/bin/bash# filename: msec_diff.shfunction timediff() {# time format:date +"%s.%N", such as 1502758855.907197692 start_time=$1 end_time=$2 start_s=${start_time%.*} start_nanos=${start_time#*.} end_s=${end_time%.*} end_nanos=${end_time#*.} # end_nanos > start_nanos? # Another way, the time part may start with 0, which means # it will be regarded as oct format, use "10#" to ensure # calculateing with decimal if [ "$end_nanos" -lt "$start_nanos" ];then end_s=$(( 10#$end_s - 1 )) end_nanos=$(( 10#$end_nanos + 10**9 )) fi # get timediff time=$(( 10#$end_s - 10#$start_s )).$(( (10#$end_nanos - 10#$start_nanos)/10**6 )) echo $time}#start=$(date +"%s.%N")# Now exec some command#end=$(date +"%s.%N")
# here give the valuesstart=1502758855.907197692end=1502758865.066894173
timediff $start $end
執行該指令碼:
[root@xuexi ~]# bash microsecond_diff.sh9.159
可見結果精確到了毫秒級。
指令碼說明:
(1).為了計算毫秒級時間差,所以使用date +"%s.%N"格式。其中"%s"是計算從1970-01-01 00:00:00到目前時間點經過的總秒數,所以計算兩個"%s"的差值就計算出了兩個時間點的秒級時間差。"%N"是每個時間點的納秒部分,由於date命令中無法直接得到精確到毫秒的時間,因此只能通過納秒來計算並轉換,於是兩個時間點的"%N"就可以計算出納秒級的時間差。
但需要注意的是,計算納秒時間差時要考慮是否要將1秒轉換成10^9納秒,以確保納秒相減時一定得到正數值。
(2)."%N"的納秒部分如果長度小於9,將以0補齊。例如999納米,將補齊為000000999。但在數學計算時,以0開頭的數值預設會被當作八進位計算,因此需要強行保證它以10進位計算,需要使用"10#"。數學運算式相關內容參見man bash的Arithmetic Evaluation部分。
(3).由於date命令擷取到的%s和%N在同一字串內,因此需要將其分割開來,在上述指令碼中採用的是變數切分的方法。
回到系列文章大綱:http://www.cnblogs.com/f-ck-need-u/p/7048359.html
轉載請註明出處:http://www.cnblogs.com/f-ck-need-u/p/7426987.html註:若您覺得這篇文章還不錯請點擊下右下角的推薦,有了您的支援才能激發作者更大的寫作熱情,非常感謝!