The timer Decorator in Python 2026

Writing Functions Mar 16, 2026

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 @wraps to 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_timer for 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:

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices