Tutorials  /  Python

Python time sleep() function

Ccentron Redaktion · February 2024 ·4 min read ·Python, Tutorial

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.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

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.

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:

Console
# importing time module
import time

print("Before the sleep statement")
time.sleep(5)
print("After the sleep statement")

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
import time
time.sleep(0.100)

Python sleep example

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

Python
import time
startTime = time.time()
for i in range(0,5):
   print(i)
   # making delay for 1 second
   time.sleep(1)
endTime = time.time()
elapsedTime = endTime - startTime
print("Elapsed Time = %s" % elapsedTime)

This will output:

Code
0
1
2
3
4
Elapsed Time = 5.059988975524902

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:

Python
import time

for i in [ .5, .1, 1, 2]:
   print("Waiting for %s" % i , end='')
   print(" seconds")
   time.sleep(i)

This will output:

Code
Waiting for 0.5 seconds
Waiting for 0.1 seconds
Waiting for 1 seconds
Waiting for 2 seconds

Dramatic printing using sleep()

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

Console
# importing time module
import time
message = "Hi!!! I am trying to create suspense"

for i in message:
   # printing each character of the message
   print(i)
   time.sleep(0.3)

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.

Python
import time
from threading import Thread


class Worker(Thread):
    def run(self):
        for x in range(0, 11):
            print(x)
            time.sleep(1)


class Waiter(Thread):
    def run(self):
        for x in range(100, 103):
            print(x)
            time.sleep(5)


print("Staring Worker Thread")
Worker().start()
print("Starting Waiter Thread")
Waiter().start()
print("Done")

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.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren