Python sleep() function
sleep() function delays execution of current executing thread for a given interval of time. Thus,
sleep() can be used to halt the execution of a python program for definite time duration.
Python time module has a
sleep() function which halts the current thread for seconds. Number of seconds is provided as argument to
sleep(5) will delay program execution for 5 seconds.
sleep() can also accept floating values, where decimal part represents subsecond delay such as milliseconds or microseconds.
Python docs for
Delay execution for a given number of seconds. The argument may be
a floating point number for subsecond precision.
Below is an example program that uses
import time print('Sleeping for 5 seconds') time.sleep() print('Resuming program execution')
Sleeping for 5 seconds
Resuming program execution
There is an interval of 5 seconds between the two lines.
To sleep a program for milliseconds, provide a decimal value to
sleep(). Python program to delay a thread for 50 milliseconds, use below code
import time time.sleep(0.05)
Further, instead of importing time, we can directly import
sleep() function. So, to invoke sleep(), we do not need to prefix
time. every time.
Thus, below syntax is also valid
from time import sleep # sleep thread for 5 seconds sleep(5)
Python sleep() example 2
Below is an example of python
sleep() function, which prints the time and sleeps for 2 seconds. This will give you a better understanding how
import time count=0 while count < 5: count += 1 print(count, ' ', time.strftime('%I:%M:%S', time.localtime())) time.sleep(2)
Above program contains a while loop which executes for 5 times. In every iteration, it sleeps the current thread for 2 seconds and prints the current time.
Above program uses python strftime function to convert time returned by
localtime() function to string.
sleep()function delays execution of current executing thread. This means that it will delay the thread execution in which it is called.
sleep()in multi-threaded environment, below is an example program which creates two threads.
import time from threading import * def thread_one(): time.sleep(5) print('Current time in thread one: ', time.strftime('%I:%M:%S', time.localtime())) def thread_two(): time.sleep(2) print('Current time in thread two: ', time.strftime('%I:%M:%S', time.localtime())) t1 = Thread(target=thread_one) t2 = Thread(target=thread_two) print('Current time: ', time.strftime('%I:%M:%S', time.localtime())) t1.start() t2.start()
Current time: 09:47:07
Current time in thread two: 09:47:09
Current time in thread one: 09:47:12
Thread two sleeps for 2 seconds while thread one sleeps for 5 seconds and this is also evident from the output.
Hope the article was useful.