Problem Statement
Show how to write a decorator that times a function and explain concerns.
Explanation
Wrap the target function, record start and end times, and return the original result. Preserve metadata like name and docstring using functools.wraps so debugging and help stay meaningful.
Be careful with arguments and return values, and consider thread safety or async functions. For heavy production use, prefer proven libraries or add configuration toggles to disable timing in hot paths.
Code Solution
SolutionRead Only
import time, functools
def timed(fn):
@functools.wraps(fn)
def wrap(*a, **k):
t0=time.perf_counter()
try:
return fn(*a, **k)
finally:
dt=time.perf_counter()-t0
print(fn.__name__, 'took', dt)
return wrap