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

112,973

Solution 1

The accuracy of the time.sleep function depends on your underlying OS's sleep accuracy. For non-realtime OS's like a stock Windows the smallest interval you can sleep for is about 10-13ms. I have seen accurate sleeps within several milliseconds of that time when above the minimum 10-13ms.

Update: Like mentioned in the docs cited below, it's common to do the sleep in a loop that will make sure to go back to sleep if it wakes you up early.

I should also mention that if you are running Ubuntu you can try out a pseudo real-time kernel (with the RT_PREEMPT patch set) by installing the rt kernel package (at least in Ubuntu 10.04 LTS).

EDIT: Correction non-realtime Linux kernels have minimum sleep interval much closer to 1ms then 10ms but it varies in a non-deterministic manner.

Solution 2

People are quite right about the differences between operating systems and kernels, but I do not see any granularity in Ubuntu and I see a 1 ms granularity in MS7. Suggesting a different implementation of time.sleep, not just a different tick rate. Closer inspection suggests a 1μs granularity in Ubuntu by the way, but that is due to the time.time function that I use for measuring the accuracy. Linux and Windows typical time.sleep behaviour in Python

Solution 3

Here's my follow-up to Wilbert's answer: the same for Mac OS X Yosemite, since it's not been mentioned much yet.Sleep behavior of Mac OS X Yosemite

Looks like a lot of the time it sleeps about 1.25 times the time that you request and sometimes sleeps between 1 and 1.25 times the time you request. It almost never (~twice out of 1000 samples) sleeps significantly more than 1.25 times the time you request.

Also (not shown explicitly) the 1.25 relationship seems to hold pretty well until you get below about 0.2 ms, after which it starts get a little fuzzy. Additionally, the actual time seems to settle to about 5 ms longer than you request after the amount of time requested gets above 20 ms.

Again, it appears to be a completely different implementation of sleep() in OS X than in Windows or whichever Linux kernal Wilbert was using.

Solution 4

From the documentation:

On the other hand, the precision of time() and sleep() is better than their Unix equivalents: times are expressed as floating point numbers, time() returns the most accurate time available (using Unix gettimeofday where available), and sleep() will accept a time with a nonzero fraction (Unix select is used to implement this, where available).

And more specifically w.r.t. sleep():

Suspend execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system.

Solution 5

Why don't you find out:

from datetime import datetime
import time

def check_sleep(amount):
    start = datetime.now()
    time.sleep(amount)
    end = datetime.now()
    delta = end-start
    return delta.seconds + delta.microseconds/1000000.

error = sum(abs(check_sleep(0.050)-0.050) for i in xrange(100))*10
print "Average error is %0.2fms" % error

For the record, I get around 0.1ms error on my HTPC and 2ms on my laptop, both linux machines.

Share:
112,973

Related videos on Youtube

Claudiu
Author by

Claudiu

Graduated from Brown University. E-mail: [email protected]

Updated on February 22, 2022

Comments

  • Claudiu
    Claudiu over 2 years

    I can give it floating point numbers, such as

    time.sleep(0.5)
    

    but how accurate is it? If i give it

    time.sleep(0.05)
    

    will it really sleep about 50 ms?

  • Glenn Maynard
    Glenn Maynard almost 15 years
    Empirical testing will give you a very narrow view. There are many kernels, operating systems and kernel configurations that affect this. Older Linux kernels default to a lower tick rate, which results in a greater granularity. In the Unix implementation, an external signal during the sleep will cancel it at any time, and other implementations might have similar interruptions.
  • Glenn Maynard
    Glenn Maynard almost 15 years
    The documentation says otherwise: > The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine.
  • Glenn Maynard
    Glenn Maynard almost 15 years
    Actually, Linux kernels have defaulted to a higher tick rate for quite a while, so the "minimum" sleep is much closer to 1ms than 10ms. It's not guaranteed--other system activity can make the kernel unable to schedule your process as soon as you'd like, even without CPU contention. That's what the realtime kernels are trying to fix, I think. But, unless you really need realtime behavior, simply using a high tick rate (kernel HZ setting) will get you not-guaranteed-but-high-resolution sleeps in Linux without using anything special.
  • Ryu
    Ryu almost 15 years
    Well of course the empirical observation is not transferable. Aside from operating systems and kernels there are a lot of transient issues that affect this. If hard real time guarantees are required then the whole system design from hardware up needs to be taken into consideration. I just found the results relevant considering the statements that 10ms is the minimum accuracy. I'm not at home in the Windows world, but most linux distros have been running tickless kernels for a while now. With multicores now prevalent it's pretty likely to get scheduled really close to the timeout.
  • Nick Bastin
    Nick Bastin almost 15 years
    Ah fair point, fixed the post, although getting longer sleeps() is much more likely than shorter ones.
  • Joseph Lisee
    Joseph Lisee almost 14 years
    Yes you are right, I tried with Linux 2.6.24-24 and was able to get pretty close to 1000 Hz update rates. At the time I was doing this I was also running the code on Mac and Windows, so I probably got confused. I know windows XP at least has a tick rate of about 10ms.
  • Dave
    Dave over 12 years
    Two and a half years later ... the documentation still lies. On Windows, signals will not terminate sleep(). Tested on Python 3.2, WinXP SP3.
  • jleahy
    jleahy almost 11 years
    It's interesting how Linux has chosen to always sleep for slightly longer than requested, whereas Microsoft have chosen the opposite approach.
  • underrun
    underrun over 10 years
    @jleahy - the linux approach makes sense to me: sleep is really a release of execution priority for an amount of time after which you once again submit yourself to the will of the scheduler (which may or may not schedule you for execution right away).
  • Diego Herranz
    Diego Herranz over 10 years
    Can anyone explain the "because any caught signal will terminate the sleep() following execution of that signal’s catching routine"? Which signals is it referring to? Thanks!
  • ArianJM
    ArianJM about 10 years
    Signals are like notifications that the OS manages (en.wikipedia.org/wiki/Unix_signal), it means that if the OS caught a signal, the sleep() is finished after treating that signal.
  • markmnl
    markmnl about 10 years
    On Windows 8 I get just under 2ms
  • markmnl
    markmnl about 10 years
    On Windows 8 I do not see Windows sleeping for less than than the time requested also I am able to sleep for less than 1ms but anywhere below 1ms I get 0.00009ms! (perhaps it is not sleeping at all)
  • markmnl
    markmnl about 10 years
    Yes but signals pre-empting sleep is unusal, e.g. KILL, the documentation also says: "Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system." which is more typical.
  • markmnl
    markmnl about 10 years
    Also the accuracy is not just dependent on the OS but what the OS is doing on both Windows and Linux if they are busy doing something more important sleep() from the docs "the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system".
  • schlenk
    schlenk over 9 years
    Singnals and Windows is just silly. On Windows the Python time.sleep() waits on a ConsoleEvent to capture stuff like Ctrl-C.
  • Tim Supinie
    Tim Supinie almost 9 years
    I gave another answer to this question using OS X Yosemite. Completely different behavior from either Windows or Linux.
  • jfs
    jfs almost 9 years
    how did you get the results? Could your provide the source code? The graph looks like an artifact of using different timers for measuring the time and the sleep (In principle, you could even use the drift between the timers as a source of randomness).
  • jfs
    jfs almost 9 years
    Could you upload the source code for the benchmark to github/bitbucket?
  • jfs
    jfs almost 9 years
    I've tried it on my machine. The result is similar to @Wilbert's answer.
  • Wilbert
    Wilbert almost 9 years
    @J.F. Sebastian - The function that I used is in socsci.ru.nl/wilberth/computer/sleepAccuracy.html . The third graph there shows an effect similar to what you see, but of only 1‰.
  • jfs
    jfs almost 9 years
    @Wilbert: time.time() on Windows might be worse than on Linux. Have your tried to run it using timeit.default_timer instead?
  • Wilbert
    Wilbert almost 9 years
    @J.F. Sebastian I use time.clock() on windows
  • Yann Vernier
    Yann Vernier almost 7 years
    CPython time.sleep() uses milliseconds on Windows, so that explains the lack of sub-millisecond sleeps.
  • jfs
    jfs almost 7 years
    @Dave: Python 3.5: "The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception"
  • Agustin Barrachina
    Agustin Barrachina over 4 years
    How did you test it?
  • Mikko Rantalainen
    Mikko Rantalainen about 4 years
    I'd guess that the sleep itself is accurate but Mac OS X scheduling is not accurate enough to provide CPU fast enough so that the wake from the sleep is delayed. If accurate wake up time is important, it seems that sleep should be set to 0.75 times the actually requested and check the time after wake up and repeatedly sleep for less and less at time until the correct time.
  • Jodo
    Jodo over 2 years
    Why is not just this implemented behind time.sleep()? This works so much better for short sleep values.
  • Mlody87
    Mlody87 over 2 years
    great answear. Thank you! This is what I looking for :)
  • iperov
    iperov about 2 years
    that's weird, because sleep should transfer control to OS in order to handle IO.