Python Friday #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.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

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:

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:

 

Conclusion

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

2 thoughts on “Python Friday #61: Slow Down Your Python Code”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.