Introduction
In programming, it is often necessary to introduce delays or pauses within a program’s execution. This could be for various reasons such as simulating real-world time passing, waiting for resources to become available, or simply to reduce CPU usage during idle periods. In Python, this can be achieved using the time
module and other techniques like threading.
This tutorial will guide you through different methods of implementing delays in your Python programs, focusing on how to pause execution for a specified number of milliseconds.
Using the Time Module
The most common way to introduce a delay is by using the sleep()
function from the time
module. This function suspends program execution for a given number of seconds.
Basic Usage of time.sleep()
import time
# Sleep for 50 milliseconds
time.sleep(0.05) # 50 ms = 0.05 seconds
Here, time.sleep()
takes an argument in seconds. To pause the execution for 50 milliseconds (ms), you convert it to seconds by dividing by 1000 (50 / 1000
).
Importing Specific Functions
You can also import just the sleep
function from the time
module if you prefer not to use the entire module:
from time import sleep
# Sleep for 50 milliseconds
sleep(0.05)
Handling Precise Delays with time.monotonic()
While time.sleep()
is straightforward, it may not always provide precise delays due to the operating system’s task scheduler and other processes that might delay its execution.
For more precise timing control, especially in loops or when you need consistent intervals, use time.monotonic()
:
from time import monotonic
def run_for_duration(duration):
start_time = monotonic()
while True:
current_time = monotonic()
if current_time - start_time >= duration:
print(f"Ran for {duration} seconds.")
break
# Run the function with a 50 milliseconds delay
run_for_duration(0.05)
time.monotonic()
provides a way to measure time intervals without being affected by system clock changes.
Introducing Delays with Threading
Python’s threading
module allows you to run functions after a specified period using the Timer
class, which is particularly useful for non-blocking delays:
from threading import Timer
def greet():
print("Hello")
# Create a timer that executes `greet()` after 50 milliseconds
t = Timer(0.05, greet)
t.start()
In this example, the program continues running other tasks while waiting to execute greet()
after 50 milliseconds.
Considerations
-
Precision: Remember that while these methods can pause execution, they may not always be precise due to OS scheduling.
-
Use Cases: Choose between
time.sleep()
,monotonic()
, or threading based on your application’s needs for precision and responsiveness. -
Blocking vs Non-blocking: Use
sleep()
when you want the program to block during the delay. For non-blocking delays, consider using a separate thread withTimer
.
Conclusion
Introducing delays in Python can be accomplished through various methods depending on your specific requirements. Whether it’s blocking execution with time.sleep()
, measuring time intervals precisely with monotonic()
, or handling asynchronous tasks with threading and Timer
, understanding these tools allows you to control program flow effectively.
By mastering these techniques, you’ll be able to create more robust and responsive Python applications tailored to real-world timing needs.