为什么 sleep 函数睡眠不一致?

2024-02-12

import time
from time import sleep
from datetime import datetime

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

它给出输出

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

跳过 52 第二行。


三个原因:time.sleep() is 不精确,您的计算机始终在任意数量的进程之间切换,并执行其余代码(查找datetime.now参考,调用now()方法,查找strftime属性,并调用strftime()带有字符串参数的方法,并打印最后一次调用的结果)也需要一些时间来执行。

See the time.sleep()功能文档 https://docs.python.org/3/library/time.html#time.sleep:

实际的暂停时间可能小于请求的时间,因为任何捕获的信号都会终止sleep()执行该信号的捕获例程后。此外,由于系统中其他活动的调度,暂停时间可能比请求的时间长任意量。

两次之间所经过的确切时间量将会有所不同datetime.now() calls.

因此,您的 1 秒睡眠可能需要比一秒长一点点的时间,并且打印出每次迭代的时间需要另外一点点。因此,有时这意味着您从一秒的最后微秒跳到此后第二秒的第一微秒,并且时间显示似乎跳过了一秒。

当您看到 2 秒的“跳跃”时,将打印以下脚本:

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

循环必须做更多的工作,因此它可能会更频繁地打印。

对我来说,在 Python 2.7 上,运行几分钟后,输出:

Time delta > 1s: 1.001061

so the display可能跳了 2 秒,但这些步骤之间的实际时间差约为 1 秒、1 毫秒和 61 微秒。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 sleep 函数睡眠不一致? 的相关文章

随机推荐