Python's time module has a handy function called sleep(). Essentially, as the name implies, it pauses your Python program. time.sleep() is the equivalent to the Bash shell's sleep command. Almost all programming languages have this feature, and is used in many use-cases.

Python's time.sleep() Syntax

This is the syntax of the time.sleep() function:

time.sleep() Arguments

  • secs - The number of seconds the Python program should pause execution. This argument should be either an int or a float.

Using Python's time.sleep()

Here's a quick, simple example to the syntax:

More Advanced Syntax

Here's a more advanced example. It takes user input, and asks you how long you want to sleep(). It also proves how it works, by printing out the timestamp before, and after the time.sleep() call. Note that Python 2.x uses the raw_input() function to get user input, whereas Python 3.x uses the input() function.

The Accuracy of time.sleep()

The time.sleep() function uses the underlying operating system's sleep() function. Ultimately there are limitations of this function. For example on a standard Windows installation, the smallest interval you may sleep is 10 - 13 milliseconds. The Linux kernels tend to have a higher tick rate, where the intervals are generally closer to 1 millisecond. Note that in Linux, you can install the RT_PREEMPT patch set, which allows you to have a semi-realtime kernel. Using a real-time kernel will further increase the accuracy of the time.sleep() function. Generally however, unless you want to sleep for a very small period, you can generally ignore this information.

Here's a few links on the information above:

About The Author