SyntaxStudy
Sign Up
Python Intermediate 3 min read

Timing Decorator

Timing Decorator

A timing decorator measures how long a function takes to run — a simple profiling tool.

Example
import time, functools

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        print(f"{func.__name__} took {end - start:.4f}s")
        return result
    return wrapper

@timer
def slow():
    time.sleep(0.1)

slow()  # slow took 0.1003s
Pro Tip

Use time.perf_counter() for the most accurate wall-clock timing.