Sea*_*898 3 bash datetime wait milliseconds
我在问如何等待下一整秒?我不是说睡1!例如,我们有时间 07:45:06.729。最后 729 表示毫秒。那么我怎么能说等到下一整秒呢?这将是 07:45:07.000
谢谢 ;)
这就像马特的回答,但没有忙着等待尝试早起。这简化了的东西很多,因为我们从来没有计较什么,但当前时间的分数第二部分。
使用 GNUdate +%N获取当前时间的纳秒部分,sleep对于 1 - 即。
sleep_to_next_second(){
#TODO: check for 0000 and don't sleep at all, instead of for 0.10000
sleep 0.$(printf '%04d' $((10000 - 10#$(date +%4N))))
}
Run Code Online (Sandbox Code Playgroud)
(修正:为了修复特殊情况的错误,你只需对 0000 进行文本比较。如果是这样,你已经在一秒钟的开始;不要睡觉。所以将 printf 结果捕获到一个local duration=$(...)变量中,或printf -v duration打印到变量中。)
诀窍是:
带前导零的数字被视为在bash算术背景下八进制,所以在使用10#$date以武力base10。
由于 bash 只能进行整数数学运算,因此显而易见的是使用定点千分之一秒之类的,并加上前导小数点。这使得前导零必不可少,以便您睡眠 0.092 秒,而不是 0.92 秒。我曾经printf '%04d'格式化我的数字。
实验测试:
# echo instead of sleep to see what numbers we generate
while true;do echo 0.$(printf '%04d' $((10000 - 10#$(date +%4N))));done
...
0.0049
0.0035
0.0015
0.10000 ##### minor bug: sleeps for 0.1 sec if the time was bang-on a ten-thousandth
0.9987
0.9973
0.9960
while true;do date +"%s %N"; sleep 0.$(printf '%04d' $((10000 - 10#$(date +%4N))));done
1445301422 583340443
1445301423 003697512
1445301424 003506054
1445301425 003266620
1445301426 003776955
1445301427 003921242
1445301428 003018890
1445301429 002652820
# So typical accuracy is 0.003 secs after the rollover to the next second, on a near-idle desktop
Run Code Online (Sandbox Code Playgroud)
Ubuntu 15.04:Linux 3.19 上的 GNU bash/date/sleep,在 Intel i5-2500k 上,空闲频率为 1.6GHz,turbo 频率为 3.8GHz。