Python sleep() function
Python 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()
.
Thus, 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 sleep()
state,
Suspend execution of the calling thread for the given number of seconds. The argument may be
a floating point number for subsecond precision.
Below is an example program that uses
sleep()
function
import time print('Sleeping for 5 seconds') time.sleep() print('Resuming program execution')
Output is
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() for 10 seconds
Below is an example of python sleep()
function, which prints the time and sleeps for 10 seconds. This will give you a better understanding how sleep()
works.
import time count=0 while count < 5: count += 1 print(count, ' ', time.strftime('%I:%M:%S', time.localtime())) time.sleep(10)
Above program contains a while loop which executes for 5 times. In every iteration, it sleeps the current thread for 10 seconds and prints the current time.
Output is
1 05:49:33
2 05:49:43
3 05:49:53
4 05:50:03
5 05:50:13
Above program uses python strftime() function to convert time returned by localtime()
function to string.
Python
sleep()
function delays execution of current executing thread. This means that it will delay the thread execution in which it is called.To demonstrate
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()
Output is
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.