Python sleep()
Last updated
Was this helpful?
Last updated
Was this helpful?
The sleep() function suspends (waits) execution of the current thread for a given number of seconds.
Python has a module named which provides several useful functions to handle time-related tasks. One of the popular functions among them is sleep()
.
The sleep()
function suspends execution of the current thread for a given number of seconds.
Here's how this program works:
"Printed immediately"
is printed
Suspends (Delays) execution for 2.4 seconds.
"Printed after 2.4 seconds"
is printed.
As you can see from the above example, sleep()
takes a floating-point number as an argument.
Before Python 3.5, the actual suspension time may be less than the argument specified to the time()
function.
Since Python 3.5, the suspension time will be at least the seconds specified.
When you run the program, the output will be something like:
Here is a slightly modified better version of the above program.
Before talking about sleep()
in multithreaded programs, let's talk about processes and threads.
A computer program is a collection of instructions. A process is the execution of those instructions.
A thread is a subset of the process. A process can have one or more threads.
All the programs above in this article are single-threaded programs. Here's an example of a multithreaded Python program.
When you run the program, the output will be something like:
The above program has two threads t1 and t2. These threads are run using t1.start()
and t2.start()
statements.
Note that, t1 and t2 run concurrently and you might get different output.
The sleep()
function suspends execution of the current thread for a given number of seconds.
In case of single-threaded programs, sleep()
suspends execution of the thread and process. However, the function suspends a thread rather than the whole process in multithreaded programs.
The above program has two threads. We have used time.sleep(0.5)
and time.sleep(0.75)
to suspend execution of these two threads for 0.5 seconds and 0.7 seconds respectively.
In the above program, we computed and printed the current local time inside the infinite . Then, the program waits for 1 second. Again, the current local time is computed and printed. This process goes on.
To learn more, visit .
Visit this page to learn more about .