Python Certification Training for Data Scienc ...
- 52k Enrolled Learners
- Live Class
At times, we require our program or sections of our program to execute after a small duration. Python makes this task effortless through time.sleep() function. This article covers the functionality of this function along with its applications.
Before moving on, let’s take a quick look at the topics covered in this article:
Let’s get started. :)
Sleep function plays a very important role in a situation where we want to halt the program flow and let other executions happen. This function is defined in both versions of python i.e 2 and 3. It belongs to the time module of Python. It basically adds a delay to the execution and it will only pause the current thread and not the whole program.
Python time.sleep() function is present in the time module of Python. Before making use of this Python function, you will need to import this module using the command:
Once this module is imported, you can make use of time.sleep() function. The syntax is as follows:
It takes one parameter which is seconds as you can see. This basically induces a delay for that many seconds during the execution. Return value for this function is void.
Let’s now take some examples to understand the working of this function.
Consider the following example that induces a delay of one second between outputs.
import time # import time module sleep_time = 1 # time to add delay after first print statement print('Hello') time.sleep(sleep_time) # sleep time print('Edureka!')
If the above code is executed it will add a delay in the program thus, the next statement will be executed after 1 second(s). For an exact delay, you can also pass floating-point values to the function. For example, if 0.1 seconds is passed then it will make a delay of 100 milliseconds.
Here is another example which will return the system time before and after the execution of the program.
# sleep demonstration import time # Start time print("The time of code execution begin is : ", end ="") print(time.ctime()) # haulting program time.sleep(6) # end time print("The time of code execution end is : ", end ="") print(time.ctime())
The time of code execution begin is : Sun Jun 23 22:36:19 2019
The time of code execution end is : Sun Jun 23 22:36:25 2019
Process returned 0 (0x0) execution time : 6.089 s
Press any key to continue . . .
Following is an example of sleep function:
import time startTime = time.time() for i in range(5, 10): print(i) # making delay for 1 second time.sleep(1) endTime = time.time() elapsedTime = endTime - startTime print("Elapsed Time = %s" % elapsedTime)
Elapsed Time = 5.006335258483887
Process returned 0 (0x0) execution time : 5.147 s
The complete execution has taken 5 seconds as the execution halted for 1 second(s) each time. Also, the extra time which required for execution is the time of system doing background operations for the programs.
Different delay time of python sleep()
Different delay times can be added between the execution of the program in Python depending on the required output. Following code demonstrate how that can be done:
import time for i in [1, 0.1, 2, 0.3]: print("I will sleep for %s" % i, end='') print(" seconds") time.sleep(i)
I will sleep for 1 seconds
I will sleep for 0.1 seconds
I will sleep for 2 seconds
I will sleep for 0.3 seconds
Process returned 0 (0x0) execution time : 3.538 s
If you want to print something in a fancy way you can do so using the sleep() function as below:
# importing time module import time message = "Some fancy character printing!" for i in message: print(i) time.sleep(0.3)
In multithreaded environment sleep() proves to be very important as while execution it can add a delay in the current thread which is being executed.
import time from threading import Thread class Runner(Thread): def run(self): for x in range(0, 7): print(x) time.sleep(2) class Delay(Thread): def run(self): for x in range(106, 109): print(x) time.sleep(7) print("Staring Runner Thread") Runner().start() print("Starting Delay Thread") Delay().start() print("Done")
Below is the output of the threading example above:
If you execute the program you will notice that the whole program doesn’t get stopped but, only the thread which was currently being executed, go ahead and give it a try.
There are many applications of this method, for example, we can use it to create a nice user interface which prints menu or the heading in some fancy way, however, one of the important application is to halt a background process which is to be executed in some interval.
import time string = "Edureka!" print_string = "" for i in range(0, len(string)): print_string = print_string + string[i] print(print_string) time.sleep(2)
As we have seen that the sleep function pauses the program for some amount of time where Python’s time module comes in handy. Let’s see a little about how can we take input from the user and use the same function dynamically.
Here’s an example of sleep that takes input from the user to add a delay between two print functions and prints the time taken to execute the print function, the following example is based on Python 3.x.
import time def sleeper(): while True: num = input('Enter wait time: ') try: num = float(num) except ValueError: print('Number only.n') continue # Run our time.sleep() command, # and show the before and after time print('Before: %s' % time.ctime()) time.sleep(num) print('After: %sn' % time.ctime()) try: sleeper() except KeyboardInterrupt: print('nnException Exiting.') exit()
Enter wait time: 1
Before: Sun Jun 23 22:44:13 2019
After: Sun Jun 23 22:44:14 2019
Enter wait time: 3
Before: Sun Jun 23 22:44:16 2019
After: Sun Jun 23 22:44:19 2019
If you want to stop execution for a smaller period of time there are limitations to this function depending on the operating system as this function uses operating systems sleep() function, in Linux the wait time can be smaller than that compared with windows.
In the above article we covered the sleep() method in python which is basically used to add a delay in program execution, this package is in the time module in Python which basically uses sleep() function of the underlying operating system. We also covered few code examples of how to use this function and took a look into applications of sleep. Demonstrated fancy ways to use this function also how it works in a threaded environment.
To get in-depth knowledge on Python along with its various applications, you can enroll for live Python online training with 24/7 support and lifetime access.
Got a question for us? Please mention it in the comments section of this “Python time sleep method in Python” blog and we will get back to you as soon as possible.