sleep() is used to delay program execution. It pauses the execution for given number of seconds. It can take floating point numbers for more precise sleep time. The suspension time may vary. It is not accurate as it uses system clock and the accuracy depends on operating system.
The system clock is an Advanced Programmable Interrupt Controller or APIC). It works internally by keeping track of CPU cycles and raising Interrupt Requests (IRQs) at programmable intervals. It interrupts whatever code the processor is currently executing, save its state, and pass control to a piece of code in the operating system.
Python calls select on Linux (and compatibles) and WaitForSingleObjectEx on Windows. Both of these are normally used for I/O and when called in a blocking way OS will put the process on hold until the data is available or the time period is expired. It will resume process once data is available or time period has expired.
The sleep() function is defined in time module.
There are two ways to include it in program
.sleep(5) ## suspend execution for five seconds
from time import sleep
sleep(5) ## suspend execution for five seconds
sleep() can take floating point numbers as argument for more precise sleep time.
time.sleep(0.100) ## Wait for 100 milliseconds
Example 1: Simple countdown timer
seconds = 5
while seconds > 0:
seconds = seconds - 1
output: 5 4 3 2 1
It will print the output with 1 second delay.
Example 2: Date and time print with 1-second interval
print("DateTime " + time.strftime("%c"))
time.sleep(1) ## delays for 1 seconds
DateTime Tue Sep 5 08:40:18 2017
DateTime Tue Sep 5 08:40:19 2017
DateTime Tue Sep 5 08:40:20 2017
DateTime Tue Sep 5 08:40:21 2017
DateTime Tue Sep 5 08:40:22 2017
And continues until stop.
Frequently Asked Python Interview Questions & Answers
Example 3: Asking user input for wait time
# Get user input
num = raw_input('How long to wait: ')
# Try to convert it to a float
num = float(num)
print('Please enter in a number.n')
# Run our time.sleep() command,
# and show the before and after time
print('Before: %s' % time.ctime())
print('After: %sn' % time.ctime())
print('nnKeyboard exception received. Exiting.')
How long to wait: 5
Before: Tue Sep 5 08:47:56 2017
After: Tue Sep 5 08:48:01 2017
How It Works:
In Python time.sleep() method blocks thread. If the program is single threaded, then the process will be also blocked. The substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps.