logo

Timing Function Execution

Here's a useful decorator that measures how long a function takes:

import time
from functools import wraps

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

Use it to find slow functions:

@timer
def slow_function():
    time.sleep(1)

slow_function()  # "slow_function took 1.0012 seconds"

This is much cleaner than adding timing code inside every function you want to measure. Apply the decorator when you need it, remove it when you don't.

Real profiling tools are more sophisticated, but this pattern works great for quick checks.

I build practical decorators like this in my Python Decorators course.