对于shell,通过date命令可以获取到当前时间,还可以设定特殊格式,看help你可以看到下面两个好用的参数:
%s seconds since '00:00:00 1970-01-01 UTC' (a GNU extension)
%N nanoseconds (000000000..999999999)
|
这里%s表示当前时间的秒数,而%N表示当前时间的纳秒部分,即1秒以下的那部分,
那么通过%s%N结合使用,我们就可以拿到纳秒级别的数据了。
#!/bin/sh
function getTiming(){
start=
$1
end=
$2
start_s=`echo
$start
| cut -d
'.'
-f 1`
start_ns=`echo
$start
| cut -d
'.'
-f 2`
end_s=`echo
$end
| cut -d
'.'
-f 1`
end_ns=`echo
$end
| cut -d
'.'
-f 2`
time_micro=$(( (10
#$end_s-10#$start_s)*1000000 + (10#$end_ns/1000 - 10#$start_ns/1000) ))
time_ms=`expr
$time_micro
/1000 | bc `
echo
"$time_micro microseconds"
echo
"$time_ms ms"
}
begin_time=`date +
%s
.
%N
`
sleep
10
end_time=`date +
%s
.
%N
`
getTiming
$begin_time
$end_time
|
执行脚本,看到输出结果了么?
10001430 microseconds
10001 ms
|
ok,搞定。
对不同单位的时间有所混淆么?下面是备忘。
1s=1000ms
1ms=1000 microseconds
1microsecond=1000 nanoseconds
参考资料:http://blog.youkuaiyun.com/gengshenghong/article/details/7583580
转载请注明出处:
http://www.cnblogs.com/liyuxia713/