Time a Function in Python 2026

Writing Functions Mar 16, 2026

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 @wraps to 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 of time.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_timer decorator
  • 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:

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