DEV Community

Cover image for time.sleep in Python
bluepaperbirds
bluepaperbirds

Posted on

time.sleep in Python

Python has a module to deal with time. This lets you pause/wait some time in your code. To do this, first import the time module

#!/usr/bin/python3
import time

Then you can use the method sleep().

Pause in Python

To sleep or wait, you can use time.sleep()

time.sleep(secs)

To sleep for five seconds

time.sleep(5)

You can also use this to sleep milliseconds

time.sleep(.500)

Thus, the parameter seconds can be either an integer or floating point number.

Pause vs threading

To be clear, it pauses the whole program: "Suspend execution of the calling thread". That means that while it is in the sleep method, it does absolutely nothing, not even listen to keyboard or mouse input.

If you want to do several things at once, look into threading. Every task runs in a thread, so the program could be pausing while still getting keyboard input or receiving to network data.

threading

How accurate is time.sleep() ?

The sleep method in the Python time module uses the operating systems sleep() function. In other words, the systems sleep code.

Because operating systems are not accurate like an atomic clock, they have some delay. But don't worry, this delay is usually 1-10 milliseconds and does not matter for 99% of the apps.

Related links:

Top comments (0)