Inaccurate time.sleep() with Python 3.x and Windows 7

↘锁芯ラ 提交于 2019-12-08 13:19:29
pvg

Python makes very few guarantees about how these calls will behave, especially cross-platform. There are two things that can potentially go wrong here - time.time()'s resolution is worse than the resolution you're trying to achieve or sleep's resolution is.

Sleep should be roughly at least 1 to 2 ms accurate on recent platforms as reported here:

How accurate is python's time.sleep()?

This leaves time.time(). The documentation for this particular call warns the accuracy may be poor:

Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

Fortunately, a higher resolution clock API is provided in time.perf_counter() which attempts to access the highest resolution clock available on platform. From the documentation:

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In the case of Windows, this seems to be better than 60Hz which corrects your problem.

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