一个准确的python睡眠函数 [英] An accurate python sleep function

查看:68
本文介绍了一个准确的python睡眠函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过 time.sleep(),但它的准确性简直是垃圾.考虑这个循环,例如:

I've tried time.sleep(), but its accuracy is total garbage. Consider this loop, for instance:

for i in range(10000000):
    print(i)
    sleep(.334)

观察它打印的数字.如果它像我的电脑一样,它甚至不是远程正常的.这个函数应该是准确的吗?我在系统中的某个地方发现了错误吗?

Watch the numbers it prints. If it's anything like my computer, it's not even remotely regular. Is this function supposed to be accurate? Have I found a bug somewhere in my system?

如果这个函数不应该是准确的,那么哪个函数会更准确?

If this function is not supposed to be accurate, what function would be more accurate?

推荐答案

如果您只是查看输出,缓冲可能会使它显得有些紧张.您可以尝试显式刷新输出,但随后您也受制于显示输出的任何内容.我什至可能会猜测您正在浏览器中使用 Jupyter Notebook,它在更新时也会有一堆缓冲/延迟.

If you're just looking at the output, buffering might make it appear slightly jittery. You could try to explicitly flush the output, but then you're also at the mercy of whatever is displaying the output. I might even hazard a guess that you're using Jupyter Notebook in your browser, which will also have a bunch of buffering/latency as it updates.

另一个问题是,如果您希望每 1/3 秒运行一次,那么您将遭受累积错误.运行循环需要一点时间,打印一个值(打印时间比其他部分多几个数量级),然后再次开始睡眠.绕过这个的一种方法是,在你完成你想做的任何事情之后(我假设一些比计数更有趣的事情),计算到下一个 1/3 秒的时间并睡眠这段时间.类似的东西:

Another issue is that if you expect to be running every 1/3 of a second, is that you will suffer from accumulated errors. It will take a little time to run the loop, print a value (printing will take orders of magnitude more time than the other parts), then start to sleep again. A way to bypass this would be that after you finish doing whatever you want to do (I assume something more interesting than count), compute the time until the next 1/3rd of a second and sleep for that amount of time. Something like:

import random
import time

sleep_until = time.monotonic() + 1/3

for n in range(100):
    print(time.monotonic() % 100, n)
    time.sleep(random.random() / 4) # some "work"

    now = time.monotonic()
    if sleep_until > now:
        time.sleep(sleep_until - now)
    else:
        pass
        #print('task took too long')
    sleep_until += 1/3

对我来说,它给出了类似的东西:

For me it gives something like:

48.34696656104643 0
48.68041984003503 1
49.08346292399801 2
49.41925806296058 3
49.72542790300213 4
50.07280854298733 5
50.41882419097237 6
50.74827564903535 7
51.08352101803757 8
51.41813271504361 9
51.75208444998134 10
52.08399672002997 11
52.41870043799281 12

所以它会反弹一点(我也在 Jupyter 中运行它,这可能会有所贡献),但不会在运行时累积错误.

So it bounces around a bit (I'm also running this in Jupyter, which may contribute), but won't stack up error as it runs.

真正的问题是你想做什么?

这篇关于一个准确的python睡眠函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆