Python time sleep() | time.sleep() Method in Python
In some cases, we need our sections or program to get executed after some period of time. It is made possible through Python’s time.sleep() function. In this tutorial, we will learn about the Python time Sleep() | time.Sleep() Method in Python in depth.
What is the use of Python time.sleep()?
Sleep functions are one of the critical aspects needed when there is s purpose of stopping the program flow and require the other executions to occur. Python time.sleep() function is characterized in both of the Python versions, namely 2 and 3. The function joins the Python’s time module. It generally provides a delay in executing the programs, it pauses only the running thread and let the remaining program to run.
Python Time Module:
The time.sleep() function in Python belongs to Python’s time module. You need to make use of the following command to make use of the Python function.
You can use the time.sleep() function once after the module is imported. The syntax using the time.sleep() function is
The functions take a single parameter. In the above syntax, seconds are the parameter. It generally produces a stop in the program for the particular seconds during the program execution. A void is the return value for the Python function. Let me explain this with practical examples for clear understanding.
Python time.sleep() function examples:
In the below example, we have produced a delay of two seconds between the results.
import time # time module importing sleep_time = 2 # delay time added after first print statement print('Welcome to') time.sleep(sleep_time) # sleep time print('Gangboard!')
Once the above program is executed, the program will be delayed for two seconds, and the next statement will be executed after two seconds. If you need the delay to be exact, you can make use of the floating values to the time.sleep() function. For instance, if 0.2 seconds is passed, then the program will be delayed for 200 milliseconds.
Let’s check another example in which the functions returns the system time both before and after the program execution.
# sleep demonstration import time # Start time print("The time of program code execution begin is : ", end ="") print(time.ctime()) # haulting program time.sleep(8) # end time print("The time of program code execution end is : ", end ="") print(time.ctime())
The time of program code execution begin is: Fri Dec 20 08:20:20 2019 The time of program code execution end is: Fri Dec 20 08:20:28 2019 Process returned 0(0X)) execution time: 8.089 s Press any key to continue…
Example for Sleep:
import time startTime = time.time() for x in range(6, 12): print(x) # making delay for 1 second time.sleep(1) endTime = time.time() elapsedTime = endTime - startTime print("Elapsed Time = %s" % elapsedTime)
6 7 8 9 10 11 Elapsed Time = 6.006335258483887 Process returned 0 (0x0) execution time : 6.147 s
The entire execution has taken 6 seconds as the code execution was stopped or one second each time. The additional time needed for code execution is the system time that does the background program operations.
A different delay time of Python sleep()
Depending on the exact output required, there can be different delay times added between the program execution in Python. The code below explains the process in a clear way.
import time for x in [1, 0.2, 2, 0.4]: print("I go sleep for %s" % x, end='') print(" seconds") time.sleep(x)
I go sleep for 1 seconds I go sleep for 0.2 seconds I go sleep for 2 seconds I go sleep for 0.4 seconds Process returned 0(0X0) execution time: 3.638s
You can make use of the following sleep() function if you need to print in a fancy way.
# importing time module import time message = "printing some fancy characters!" for x in message: print(x) time.sleep(0.2)
Executing the above code means you can see a delay in each of the characters that are printed infancy.
Python Thread sleep:
The multithread environment sleep() is capable of adding the delay in the present thread that is getting executed currently. Let’s look at this with an example.
import time from threading import Thread class Runner(Thread): def run(self): for i in range(0, 7): print(i) time.sleep(2) class Delay(Thread): def run(self): for i in range(106, 109): print(i) time.sleep(7) print("Runner Thread start") Runner().start() print("Delay Thread Start") Delay().start() print("completed")
Runner Thread start 0 Delay thread Start 106 Completed 1 2 3 107 4 5 6 108 Process returned 0(0X0) execution time: 21.23 s Press any key to continue…
While executing the program, you can see the just the thread presently getting executed stops and not the whole thread.
There are several applications available for this method. Let’s check out an example. We can use the application to develop an excellent user interface that can print heading or menu with fancy characters. Still, one of the critical applications is going to stop the background process that is to be executed in a defined interval.
import time string = "Gangboard!" print_string = "" for x in range(0, len(string)): print_string = print_string + string[x] print(print_string) time.sleep(2)
G Ga Gan Gang Gangb Gangbo Gangboa Gangboar Gangboard!
In the above example, the sleep functions halt the program as per the defined time. This can be done dynamically too. Let’s check them below.
Dynamic Sleep Example:
The example of sleep which takes the user’s input to add a delay between any dual print functions and then prints the total time is taken for executing those two print functions. Here is an example that is based on Python 3.x
import time def sleeper(): while True: num = input('List wait time: ') try: num = float(num) except ValueError: print('Number only.n') continue print('Before: %s' % time.ctime()) time.sleep(num) print('After: %sn' % time.ctime()) try: sleeper() except KeyboardInterrupt: print('nnException Exiting.') exit()
List wait time: 1 Before: Fri Dec 20 08:44:13 2019Sun Jun 23 22:44:13 2019 After: Fri Dec 20 08:44:14 2019 List wait time: 3 Before: Fri Dec 20 08:44:16 2019 After: Fri Dec 20 08:44:19 2019
If you require to stop the execution for a specific time limit, then there are some limitations with the functions based on the operating system. The function makes use of the operating system sleep() function. While considering Linux, the wait time is less when compared to the windows.
I hope the above tutorial helped you to know about the Python time Sleep() | time.Sleep() Method in Python in depth. If you have queries on the topic, ask us in the comment section below.