Python Tips and Gotchas #2 - Microseconds and accuracy in time.sleep()

The sleep function in the time module can be used to halt execution for a given number of seconds. But it is easy to miss that the argument can be a float as well. In other words, you can use microseconds and not just whole seconds:

1
2
import time
time.sleep(0.05)

This can be useful when you need to make a short pause but not necesseraly in seconds. For example if you are hammering an internal or external API in some batch job it could be useful to let the other end catch its breath for a while by pausing for a few hundred microseconds.

Though you should not trust the accuracy of this function down to the microseconds, wether you are using seconds or microseconds. Since Python’s sleep() uses the current operating system’s underlying sleep-functionality, unless you are using a real-time system this function will not be 100% accurate:

1
2
3
4
5
6
7
8
9
import time
import timeit

time = timeit.timeit('time.sleep(0.05)', number=100)
print(time)
time = timeit.timeit('time.sleep(0.05)', number=100)
print(time)
time = timeit.timeit('time.sleep(0.05)', number=100)
print(time)
5.273200581
5.261563578
5.282216143000001