Timer in Python
Creating a timer in Python can be achieved in various
ways, depending on whether we need a countdown timer,
a stopwatch, or a way to measure code execution time.
1. Countdown Timer:
To create a countdown timer, the time module is
commonly used.
import time
def countdown(seconds):
while seconds > 0:
mins, secs = divmod(seconds, 60)
timer_display = f"{mins:02d}:{secs:02d}"
print(timer_display, end='\r') # Overwrites the previous line
[Link](1)
seconds -= 1
print("Time's up!")
# Example usage:
countdown(10) # Counts down from 10 seconds
2. Stopwatch / Elapsed Time:
To measure the elapsed time between two points in our
code, we can use time.perf_counter() for high-resolution
timing or [Link]() for general-purpose timing.
import time
# Using time.perf_counter() for precise timing
start_time_perf = time.perf_counter()
# ... code to be timed ...
[Link](2) # Simulate some work
end_time_perf = time.perf_counter()
elapsed_time_perf = end_time_perf - start_time_perf
print(f"Elapsed time (perf_counter): {elapsed_time_perf:.4f}
seconds")
# Using [Link]() for general timing
start_time_general = [Link]()
# ... code to be timed ...
[Link](1) # Simulate some work
end_time_general = [Link]()
elapsed_time_general = end_time_general - start_time_general
print(f"Elapsed time ([Link]): {elapsed_time_general:.4f}
seconds")
3. Timer Classes, Decorators, and Context
Managers:
For more advanced and reusable timing solutions, we can
implement custom timer classes, decorators, or context
managers. These offer structured ways to apply timing
logic to functions or code blocks.
Example of a simple timer class:
import time
class Timer:
def __init__(self):
self.start_time = None
def start(self):
self.start_time = time.perf_counter()
def stop(self):
if self.start_time is None:
raise RuntimeError("Timer not started.")
end_time = time.perf_counter()
elapsed = end_time - self.start_time
self.start_time = None # Reset for next use
return elapsed
# Example usage:
my_timer = Timer()
my_timer.start()
[Link](0.5)
duration = my_timer.stop()
print(f"Code block took {duration:.4f} seconds.")