Using timer() in Python 2026

Writing Functions Mar 16, 2026

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 @timer above 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 @timer to 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_timer version 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:

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