How do I make a Timer in Python

61    Asked by johnhi_7215 in Python , Asked on Aug 6, 2025

Whether you're building a countdown, measuring execution time, or creating scheduled delays, Python offers several ways to implement a timer. From simple time.sleep() delays to using threading.Timer or the timeit module, the approach depends on your use case.

Answered by jhone

Creating a timer in Python can be done in multiple ways, depending on your goal—whether it’s a countdown, a delay, or measuring how long something takes. Python has built-in libraries that make this quite simple and beginner-friendly.

Here are a few common ways to implement a timer:

Using time.sleep() for delays

 This is the easiest way to pause execution for a specified number of seconds.

import time
print("Timer starts")
time.sleep(5)
print("5 seconds have passed")

Using time.time() to measure elapsed time

 Great for benchmarking or checking how long a block of code takes to execute.

import time
start = time.time()
# some code
end = time.time()
print(f"Elapsed time: {end - start} seconds")

Using timeit module for accurate timing of small code snippets

 This is more precise than time.time() and is useful for performance testing.

import timeit
print(timeit.timeit("x = sum(range(100))", number=1000))

Using threading.Timer to schedule actions

 If you want a function to run after a delay without blocking other code:

from threading import Timer
def greet():
    print("Hello after 3 seconds!")
Timer(3, greet).start()

These options cover most needs, from simple delays to more advanced timed execution. Pick the one that best fits your project.



Your Answer

Interviews

Parent Categories