Python's Time.sleep() Method Waits Incorrect Amount Of Time
Solution 1:
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 inrange(4):... time.sleep(1)...print'%.3f'%(time.time()-startt)...
3.147
4.147
5.147
6.147
>>>startt = time.time()>>>for i inrange(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:
>>>deftest():... startt = time.time()...for i inrange(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 inrange(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.
Post a Comment for "Python's Time.sleep() Method Waits Incorrect Amount Of Time"