Python time sleep() With Examples

Hello everyone, hope you are learning python well. In this tutorial we will learn about python time sleep() method. Python sleep function belongs to the python time module that is already discussed earlier

Python time sleep

Python time sleep function is used to add delay in the execution of a program. We can use python sleep function to halt the execution of the program for given time in seconds. Notice that python time sleep function actually stops the execution of current thread only, not the whole program.

Python time sleep() function syntax

Python sleep() is a method of python time module. So, first we have to import the time module then we can use this method. Way of using python sleep() function is:

python time sleep, python sleep

Here the argument of the sleep() method t is in seconds. That means, when the statement time.sleep(t) is executed then the next line of code will be executed after t seconds. See the following example:

If you run the above code then you will see that the second print executes after 5 seconds. So you can make delay in your code as necessary.

The argument can be in floating value also to have more precise delay. For example you want to make delay for 100 milliseconds which is 0.1 seconds, as following:

Python sleep example

Let’s see the following example of python time sleep function.

This will output:

Elapsed time is greater than 5 because each time in the for loop, execution is halted for 1 second. The extra time is because of the execution time of the program, operating system thread scheduling etc.

Different delay time of python sleep()

Sometimes you may need to delay for different seconds of time. You can do it as follows:

This will output:

Dramatic printing using sleep()

You may need to print some message in a dramatic way, you can do it as following:

If you run the above code then, you will see that after printing every character of the message it’s taking some time, which seems like dramatic.

Python thread sleep

Python time sleep() function is very important method for multithreading. Below is a simple example showing that the python time sleep function halts the execution of current thread only in multithreaded programming.

Below image shows the output produced by above python thread sleep example.

python time sleep()

From the output it’s very clear that only the threads are being stopped from execution and not the whole program by python time sleep function.

That’s all about python time sleep function or python sleep function.

Reference: StackOverFlow Post, API Doc

By admin

Leave a Reply

%d bloggers like this: