Skip to content

#61: Slow Down Your Python Code

Python is not the fastest programming language, but sometimes your code may still run too fast. Let us look how we can tell Python to take a break.

time.sleep()

The time module of Python provides various time-related functions, like datetime and calendar. For this post we use the time.sleep() function to pause our code for a few seconds.

Since it is a built-in module, we do not need to install it with PIP. We can import time to our script and call time.sleep() with the number of seconds we want to pause our code:

1
2
3
4
5
import time

print("start")
time.sleep(2)
print("stop")

If we run our script it will take around 2 seconds from the first print statement to the second one. How long it will wait exactly can no one tell; therefore, do not use it as a clock. If you use Python 3.5 and newer, it may take longer than the specified time, while older versions may wait less than that. The change of behaviour is described in PEP 475 and affects more than just time.sleep().

If you need a shorter break, you can call sleep with a fraction of a second:

1
2
3
4
5
import time

print("start")
time.sleep(0.75)
print("stop")

Conclusion

If your Python code runs too fast, a call to time.sleep() is a simple way to slow down your code.