python logo

python pause for time


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

To pause or introduce a delay in a Python program’s execution, utilize the time.sleep(seconds) method available in the time module. This module offers various functionalities related to time such as obtaining the current time, converting epoch time, and more.

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

The time.sleep function pauses a program’s execution for a specified duration. The delay is defined in seconds. To avoid completely halting a program, consider implementing threading.

Here’s a simple demonstration of the time.sleep function:

1
2
import time
time.sleep(5) # The program will pause for 5 seconds

The time.sleep(sec) function also accepts floating-point numbers. This allows for more precise delays, such as waiting for a fraction of a second:

1
2
import time
time.sleep(0.100) # The program will pause for 100 milliseconds

Creating a straightforward countdown timer that counts from 5:

1
2
3
4
5
6
7
import time

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

Accuracy of time.sleep

The accuracy of time.sleep(seconds) varies—it doesn’t necessarily adhere to real-time measurements. Depending on the operating system, the actual pause duration might deviate slightly, possibly by a few milliseconds.

To illustrate, here’s a demonstration of attempting to wait for approximately 50 milliseconds:

1
2
3
4
Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
>>> from time import sleep
>>> sleep(0.05)

Depending solely on the sleep method won’t guarantee an exact delay of 50ms. Most computer systems have hardware constraints ranging from 1-10ms, independent of the OS. To operating systems, time.sleep() is more of a suggestion rather than a strict timing mechanism. However, it’s satisfactory for a majority of applications.

Different OS implementations might result in variations in the sleep duration.

Accuracy of time.sleep
Image courtesy of Stackoverflow.

For enhanced precision, especially at the millisecond level, one would require specialized hardware, such as an embedded system.

Next: Speech Engines with Python Tutorial






Leave a Reply: