How to Create a Timing Decorator in Python

A Python decorator that measures and prints the execution time of any function using time.perf_counter.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

24 lines
Python 3.9+
import time
from functools import wraps


def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        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


@timing_decorator
def compute_sum(n):
    return sum(range(n))


if __name__ == "__main__":
    result = compute_sum(1000000)
    print(f"Result: {result}")

Output

stdout
compute_sum took 0.034532 seconds
Result: 499999500000

How it works

The timing_decorator wraps the original function and records time.perf_counter() before and after the call. perf_counter provides the highest-resolution timer available on the platform, ideal for short intervals. Using functools.wraps preserves the original function's metadata so that debugging and introspection still work. The decorator prints the elapsed time with six decimal places, then returns the function's result unchanged.

Common mistakes

  • Using `time.time()` instead of `time.perf_counter()` for high-precision timing.
  • Forgetting to return the result from the wrapper, causing functions to return None.
  • Not using `@wraps(func)` which breaks function metadata and documentation.
  • Measuring time on I/O-bound functions without including the full wait time.

Variations

  1. Use `time.process_time()` to measure CPU time only, ignoring I/O waits.
  2. Add an optional `output` parameter to the decorator to suppress printing.
  3. Use `time.perf_counter_ns()` for nanosecond precision.

Real-world use cases

  • Profiling database queries inside a web service to log slow operations.
  • Measuring the latency of API endpoint handlers during development.
  • Benchmarking different algorithms before selecting one for production.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.