How to work with sleep or add delay in program?

What is time sleep function in python and how does it work, please explain with some examples.

Sleep function is present in time module of python. It is very useful when you are trying to add some delay in program execution. It does not stop complete program instead it just adds some delay in particular thread only. We can understand it with some examples which you see below:

 

import time

#Example:1

sleep_time = 1

print("Hello")

time.sleep(sleep_time)

print("World")


 

#Example:2

print("Execution Begins: ", end="")

print(time.ctime())

time.sleep(5)

print("Execution Ends: ", end="")

print(time.ctime())


 

#Example:3

start_time = time.time()

for i in range(1,10):

    print(i)

    #add delay for 1 sec

    time.sleep(1)

end_time = time.time()

execution_time = end_time - start_time

print("Total execution time: %s" % execution_time)

 

#Output

1

2

3

4

5

6

7

8

9

Total execution time: 9.00051474571228


 

#Example:4

import time

from threading import Thread

 

class Runner(Thread):

    def run(self):

        for i in range(0,7):

            print(i)

            time.sleep(1)

 

class Delay(Thread):

    def run(self):

        for i in range(20, 25):

            print(i)

            time.sleep(5)

 

print("Start of thread.")

Runner().start()

print("Start delay thread.")

Delay().start()

print("Program completed.")

 

#Output

Start of thread.

0

Start delay thread.

20

Program completed.

1

2

3

4

5

21

6

22

23

24


If you face any issue you can comment here and we will try to assist and solve your problem.