python logo

Python time.sleep() - Add Time Delays

Python hosting: Host, run, and code Python in the cloud!

To make a Python program delay (pause execution), use the sleep(seconds) method.  which can be found in the time module.
The time module provides many time related functionality like getting the current time, converting epoch time and others.

Related Course:
Python Programming Bootcamp: Go from zero to hero

The time.sleep pauses execution, making the program wait for the defined time. The time to wait (sleep) is defined in seconds. If you don’t want the program to completely freeze use threading instead.


import time
time.sleep(5) # Wait for 5 seconds

The time.sleep(sec) method supports floating point numbers, meaning you can make it wait half a second too


import time
time.sleep(0.100) # Wait for 100 milliseconds

A simple countdown timer from 5:


import time

seconds = 5
while seconds > 0:
print(seconds)
time.sleep(1)
seconds = seconds - 1

Accuracy


The time.sleep(seconds) is not real time. The accuracy depends on the operating system, sometimes it may be off in terms of milliseconds.

To wait about 50 milliseconds:


Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from time import sleep
>>> sleep(0.05)

You won’t get exactly 50ms if you rely on the sleep method.

Most PC machines have hardware limits in the 1-10ms range, regardless of operating system. To the operating system, time.sleep() just means a hint. It’s not a good timing mechanism, but good enough for most applications.

Operating systems may have different implementations, causing a difference in time.

time.sleep accuracy
(Image from Stackoverflow)

For higher accuracy, you need dedicated hardware (embedded system) to keep accurate time on the milliseconds level.






BackNext





Leave a Reply: