Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's time.sleep() method waits incorrect amount of time

Tags:

python

time

I've run into this problem a few times; restarting python seems to work (or ipython). But, for instance, here's one possible output of running the following code:

startt = time.time()
for i in range(4):
    time.sleep(1)
    print '%.3f'%(time.time()-startt)

I obtain:

9.989
10.989
11.990
12.991

Why does it wait so long before it begins working? Occasionally, it will start at 10 or even 11 seconds after I run the command.

I'm using Mac OS X (Mavericks), IPython 1.2.1 (with pylab), Python 2.7.5

I'm importing: os, cv2, time, random, Quartz, LaunchServies, pdb, sys, appscript, and numpy.

like image 269
eriophora Avatar asked Dec 25 '22 05:12

eriophora


1 Answers

As per the time.sleep docs:

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.

The actual wait time of time.sleep is not guaranteed and depends on how the host system is loaded. If something on your machine gets hold of the resources the Python process may get delayed until resumed.

Still, the delay of seconds is just too high. Are you by any chance trying this in the Python interactive shell? If so, it may interfere, e.g.:

>>> import time
>>> startt = time.time()
>>> for i in range(4):
...     time.sleep(1)
...     print '%.3f'%(time.time()-startt)
...
3.147
4.147
5.147
6.147
>>> startt = time.time()
>>> for i in range(4):
...     time.sleep(1)
...     print '%.3f'%(time.time()-startt)
...
4.949
5.949
6.949
7.949

Because the startt = time.time() gets evaluated before the rest of the code gets written or pasted in and evaluated, which can take seconds.

But it behaves as expected if I wrap it in a method:

>>> def test():
...     startt = time.time()
...     for i in range(4):
...         time.sleep(1)
...         print '%.3f'%(time.time()-startt)
...
>>> test()
1.000
2.000
3.000
4.000

or put into a script:

import time

startt = time.time()
for i in range(4):
    time.sleep(1)
    print '%.3f'%(time.time()-startt)

# $ python test.py
# 1.000
# 2.008
# 3.008
# 4.008

In this case the delays should be in order of milliseconds, as can be seen in the latter output. I doubt it could get to seconds.

like image 195
famousgarkin Avatar answered Dec 31 '22 13:12

famousgarkin