Python

Timing Decorator with Logger

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Drop @timed on any function and get its wall-clock duration logged on every call. Uses functools.wraps so introspection (name, docstring, signature) still works.
Python
Raw
import functools
import logging
import time

log = logging.getLogger(__name__)

def timed(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return fn(*args, **kwargs)
        finally:
            ms = (time.perf_counter() - start) * 1000
            log.info("%s took %.2f ms", fn.__qualname__, ms)
    return wrapper

@timed
def expensive(n: int) -> int:
    return sum(i * i for i in range(n))

expensive(1_000_000)
# INFO  expensive took 47.31 ms
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.