How to Create a Timing Decorator in Python
A Python decorator that measures and prints the execution time of any function using time.perf_counter.
Python code
24 linesimport time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
end = time.perf_counter()
elapsed = end - start
print(f"{func.__name__} took {elapsed:.6f} seconds")
return result
return wrapper
@timing_decorator
def compute_sum(n):
return sum(range(n))
if __name__ == "__main__":
result = compute_sum(1000000)
print(f"Result: {result}")
Output
compute_sum took 0.034532 seconds
Result: 499999500000
How it works
The timing_decorator wraps the original function and records time.perf_counter() before and after the call. perf_counter provides the highest-resolution timer available on the platform, ideal for short intervals. Using functools.wraps preserves the original function's metadata so that debugging and introspection still work. The decorator prints the elapsed time with six decimal places, then returns the function's result unchanged.
Common mistakes
- Using `time.time()` instead of `time.perf_counter()` for high-precision timing.
- Forgetting to return the result from the wrapper, causing functions to return None.
- Not using `@wraps(func)` which breaks function metadata and documentation.
- Measuring time on I/O-bound functions without including the full wait time.
Variations
- Use `time.process_time()` to measure CPU time only, ignoring I/O waits.
- Add an optional `output` parameter to the decorator to suppress printing.
- Use `time.perf_counter_ns()` for nanosecond precision.
Real-world use cases
- Profiling database queries inside a web service to log slow operations.
- Measuring the latency of API endpoint handlers during development.
- Benchmarking different algorithms before selecting one for production.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.