Why are sleep function sleeps inconsistent?

蓝咒 提交于 2021-01-20 14:10:48

问题


import time
from time import sleep
from datetime import datetime

while True: 
    print datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    sleep(1)

It gives output

2018-09-23 16:14:42
2018-09-23 16:14:43
2018-09-23 16:14:44
2018-09-23 16:14:45
2018-09-23 16:14:46
2018-09-23 16:14:47
2018-09-23 16:14:48
2018-09-23 16:14:49
2018-09-23 16:14:50
2018-09-23 16:14:51
2018-09-23 16:14:53
2018-09-23 16:14:54
2018-09-23 16:14:55
2018-09-23 16:14:56

Skipped 52 second row.


回答1:


Three reasons: time.sleep() is not precise, your computer is switching between any number of processes, all the time, and executing the rest of your code (looking up the datetime.now reference, calling the now() method, looking up the strftime attribute, and calling the strftime() method with a string argument, and printing the result of that last call) take a bit of time to execute too.

See the time.sleep() function documentation:

The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

There will be variations in the exact amount of time passed between the datetime.now() calls.

So your 1 second sleep can take a fraction longer than a second, and printing out the time each iteration takes another fraction. So sometimes that means you jump from the last microseconds of one second to the first microseconds of 2nd second after that, and the time display seems to have skipped a second.

The following script prints when you'd see a 'jump' of 2 seconds:

last = datetime.now()
while True:
    sleep(1)
    t = datetime.now()
    s_delta = t.second - last.second
    if t.second < last.second:  # delta to next minute
        s_delta += 60
    if s_delta > 1:
        print('Time delta > 1s: {:.6f}'.format((t - last).total_seconds()))
    last = t

The loop has to do more work, so it'll probably print more often.

For me, on Python 2.7, after some a few minutes running time, this outputs:

Time delta > 1s: 1.001061

so the display may have jumped 2 seconds, but the actual time difference between those steps was about 1 second, 1 millisecond, and 61 microseconds.



来源:https://stackoverflow.com/questions/53250230/why-are-sleep-function-sleeps-inconsistent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!