Using timer() in Python 2026 – Best Practices for Writing Functions
The timer() decorator is one of the most practical and commonly used decorators in Python. It helps you quickly measure and monitor the execution time of any function without cluttering your core logic with timing code.
TL;DR — How to Use timer() in 2026
- Simply place
@timerabove any function you want to time - It automatically prints the execution time using high-precision
perf_counter() - Works with both regular and async functions (with minor variations)
- Preserves the original function name and docstring
1. The Modern timer() Decorator
from functools import wraps
import time
from typing import Callable, Any
def timer(func: Callable) -> Callable:
"""Decorator that measures and 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__}() executed in {elapsed:.6f} seconds")
return result
return wrapper
2. Real Usage Examples
@timer
def heavy_computation(n: int):
"""Simulate a CPU-intensive task."""
total = 0
for i in range(n):
total += i ** 2
return total
@timer
def fetch_data_from_api(url: str):
"""Simulate an API call."""
import time
time.sleep(0.8) # Simulate network delay
return {"status": "success", "data": "sample"}
# Using the decorator
result1 = heavy_computation(10000)
result2 = fetch_data_from_api("https://api.example.com/data")
3. Best Practices for Using timer() in 2026
- Apply
@timerto functions you suspect might be slow or need optimization - Remove or comment out the decorator in production if the timing output is not needed
- For production monitoring, combine with proper logging instead of printing
- Create an
@async_timerversion for asynchronous functions - Use it during development and debugging phases
Conclusion
Using the timer() decorator is one of the simplest and most effective ways to measure function performance in Python. In 2026, it remains a go-to tool for developers who want quick insights into execution time without polluting their business logic with manual timing code.
Next steps:
- Add
@timerto your slowest or most critical functions right now - Related articles: Decorators in Python 2026 • Time a Function in Python 2026 • Writing Functions in Python 2026