Python sleep()



The sleep() method suspends the current thread's execution for a given number of seconds.

Python offers a module named time that provides different useful functions to handle time-related tasks. And one of the most used functions among them is the sleep() function.


Example: Python sleep()

In the following example, we will see how to use the sleep() method.

import time

print("This is printed immediately.")
time.sleep(5.3)
print("This is printed after 5.3 seconds.")

Output

This is printed immediately. 
This is printed after 5.3 seconds.

The above program works as follows:

  • "This is printed immediately." is printed directly.
  • Delays (waits) execution for 5.3 seconds.
  • "This is printed after 5.3 seconds."

The sleep() method can take a floating-point number as an argument.


Example: Python create a digital clock

In the following example, we will compute and print the current local time with the help of the infinite while loop.

import time

while True:
    localtime = time.localtime()
    result = time.strftime("%I:%M:%S %p", localtime)
    print(result)
    time.sleep(1)

Output

02:51:11 PM
02:51:12 PM
02:51:13 PM
02:51:14 PM
...

As we can see above, after the program computes and prints the current local time, it waits for 1 second, then compute and print the local time again. This process goes on.

Let us see a better version of the above program.

import time

while True:
    localtime = time.localtime()
    result = time.strftime("%I:%M:%S %p", localtime)
    print(result, end="", flush=True)
    print("\r", end="", flush=True)
    time.sleep(1)

Multithreading in Python

Let us 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.


Example: Python multithreading

All the above programs used in this article are single-threaded.

In the following example, we will see a multithread Python program.

import threading

def print_hello():
    for i in range(4):
        print("Hello")

def print_world():
    for i in range(4):
        print("World")

t1 = threading.Thread(target=print_hello)
t2 = threading.Thread(target=print_world)

t1.start()
t2.start()

After executing the above program, the output will be:

Hello
Hello 
World
Hello
World
World
Hello
World

As we can see above, the program has two threads, t1 and t2. These threads are started using t1.star()t and t2.start() statements.

As we can see, t1 and t2 run concurrently, and you might get different outputs on each execution.


time.sleep() in multithreaded programs

The time.sleep() function delays the current thread's execution for a given number of seconds.

In the case of a single-threaded program, the sleep() function suspends the execution of the thread and the process. However, it suspends a thread rather than the whole process in a multithreaded program.


Exmaple: sleep() in a multithreaded program

In the following example, we will see how we can use the sleep() function in a multithreaded program.

import threading
import time

def print_hello():
    for i in range(4):
        time.sleep(0.3)
        print("Hello")

def print_world():
    for i in range(4):
        time.sleep(0.4)
        print("World")

t1 = threading.Thread(target=print_hello)
t2 = threading.Thread(target=print_world)

t1.start()
t2.start()

Output

Hello 
World 
Hello 
Hello 
World
Hello
World
World

As we can see above, the program has two threads. We have used time.sleep(0.3) and time.sleep(0.4) to suspends the execution of these two threads for 0.3 and 0.4 seconds respectively.



ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.