Python time.sleep vs busy wait accuracy

ⅰ亾dé卋堺 提交于 2019-12-01 03:52:41

On Windows the OS Sleep function (which Python necessarily uses) can only wake up a thread on a multiple of the current timer interval. Typically this ranges between 1.0 ms and 15.6 ms. Lowering the timer interval can be handy because it allows for shorter sleeps, but it wastes electricity, as I wrote about in this article:

http://randomascii.wordpress.com/2013/07/08/windows-timer-resolution-megawatts-wasted/

Busy waiting may give better accuracy but is generally a horrible idea since it wastes even more electricity and steals CPU time from more deserving tasks:

https://randomascii.wordpress.com/2012/06/05/in-praise-of-idleness/

Finally, the accuracy of busy waiting will depend on what timer function you are using to get the current time, and may also depend on the timer interval:

https://randomascii.wordpress.com/2013/05/09/timegettime-versus-gettickcount/

Why do you want to sleep for such short time periods? Usually it would be better to wait for something to happen -- waiting on an event -- rather than waiting for such short time periods.

This is sort of a duplicate question, but I'll try to answer it here anyway to the best of my ability.

The sleep function is an OS call that differs from busy wait in that it doesn't block the thread. If you have a multi-threaded script though, it shouldn't block the other threads. The sleep function is inaccurate in Windows because it is not a realtime OS (not sure what that means). If you are looking strictly for accuracy of the wait, busy wait is the way to go. Otherwise, time.sleep() is probably preferred. The reason the OS call to sleep is inaccurate is probably because it relies on the OS to return at the correct time, and is reliant on the precision of the OS's scheduler.

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