Python time.sleep vs busy wait accuracy

前端 未结 2 1810
难免孤独
难免孤独 2021-01-12 00:42

I was playing around with the time.sleep function from python\'s standard library and found it inadequate for sub-ms delays. From testing I found it to actually wait 1.1-1.2

相关标签:
2条回答
  • 2021-01-12 01:32

    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.

    0 讨论(0)
  • 2021-01-12 01:43

    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.

    0 讨论(0)
提交回复
热议问题