Time a Function in Python 2026 – Best Practices for Writing Functions
Timing your functions is one of the most common and useful tasks in Python development. In 2026, the recommended way is to create a clean, reusable `@timer` decorator that uses `time.perf_counter()` for high-precision measurements.
TL;DR — Modern Timer Decorator 2026
- Use
time.perf_counter()for the most accurate timing - Always use
@wrapsto preserve function metadata - Support both synchronous and async functions
- Make the output clean and informative
1. Complete Timer Decorator
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 slow_calculation(n: int) -> int:
"""Simulate a heavy computation."""
time.sleep(0.5)
return n ** 2
@timer
def process_list(data: list) -> list:
return [x * 2 for x in data]
result1 = slow_calculation(10)
result2 = process_list(list(range(10000)))
3. Best Practices for Timing Functions in 2026
- Use
time.perf_counter()instead oftime.time()for benchmarking - Always apply
@wraps(func)to keep original function name and docstring - Keep the timer output clean and consistent across your project
- For async functions, create a separate
@async_timerdecorator - Consider logging the time instead of printing for production code
Conclusion
Timing functions is essential for performance analysis and optimization. In 2026, the cleanest and most reusable approach is to create a well-written `@timer` decorator using perf_counter() and functools.wraps. This pattern keeps your code DRY and professional.
Next steps:
- Add the
@timerdecorator to your most important or slow functions - Related articles: Decorators in Python 2026 • Writing Functions in Python 2026