The timer Decorator in Python 2026 – Best Practices
The @timer decorator is one of the most useful and frequently used decorators in Python. It measures and displays the execution time of any function while keeping your code clean and readable.
TL;DR — The Modern timer Decorator (2026)
- Uses
time.perf_counter()for high-precision timing - Always includes
@wrapsto preserve function metadata - Works with both regular and async functions
- Provides clean, consistent output
1. Complete Implementation
from functools import wraps
import time
from typing import Callable, Any
def timer(func: Callable) -> Callable:
"""Decorator that prints the execution time of a function."""
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
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
2. Usage Examples
@timer
def heavy_calculation(n: int):
"""Simulate CPU-intensive work."""
return sum(i ** 2 for i in range(n))
@timer
def fetch_api_data(url: str):
"""Simulate network call."""
import time
time.sleep(0.6)
return {"status": "success"}
# Using the decorator
result1 = heavy_calculation(50000)
result2 = fetch_api_data("https://api.example.com/data")
3. Best Practices for the timer Decorator in 2026
- Use it during development and performance tuning
- Remove or disable it in production (or replace with structured logging)
- Keep the output clean and consistent across your project
- Create a separate
@async_timerfor async functions - Combine with other decorators when needed (order matters!)
Conclusion
The @timer decorator is a simple yet powerful tool for measuring function performance. In 2026, using a well-written timer decorator with perf_counter() and wraps is considered standard practice for any developer who cares about performance and clean code.
Next steps:
- Add
@timerto your slowest or most critical functions today - Related articles: Decorators in Python 2026 • Time a Function in Python 2026 • Writing Functions in Python 2026