Blog

Python Sleep Method

  • (4.0)
  • | 927 Ratings |
  • Last Updated September 01, 2017
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.
Learn how to use Python, from beginner basics to advanced techniques, with online video tutorials taught by industry experts. Enroll for Free Python Training Demo!
 
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.

time.sleep()

The sleep() function is defined in time module.
There are two ways to include it in program
import time 
.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.
 
import time
time.sleep(0.100) ## Wait for 100 milliseconds

Example 1: Simple countdown timer

import time
 
seconds = 5
while seconds > 0:
      print(seconds)
    time.sleep(1)
    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

import time
while True:
  print("DateTime " + time.strftime("%c"))
  time.sleep(1) ## delays for 1 seconds

output: 

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

import time
 
def sleeper():
    while True:
        # Get user input
        num = raw_input('How long to wait: ')
 
        # Try to convert it to a float
        try:
            num = float(num)
        except ValueError:
            print('Please enter in a number.n')
            continue
 
        # Run our time.sleep() command,
        # and show the before and after time
        print('Before: %s' % time.ctime())
        time.sleep(num)
        print('After: %sn' % time.ctime())
 
try:
    sleeper()
except KeyboardInterrupt:
    print('nnKeyboard exception received. Exiting.')
    exit()

output :

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.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

 

Subscribe For Free Demo

Free Demo for Corporate & Online Trainings.