Timing Decorator
A timing decorator measures how long a function takes to run — a simple profiling tool.
A timing decorator measures how long a function takes to run — a simple profiling tool.
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
Use time.perf_counter() for the most accurate wall-clock timing.