1a
Write a decorator function benchmark at the top of the first cell. It returns a wrapper that calls the function with any arguments, measures the call with time.time(), prints the function's name and the elapsed seconds, and returns the function's result.
Hint 1
The slides Variable Arguments and Execution Hooks show a wrapper that takes *args, **kwargs and runs code around the call.
Hint 2
The wrapper has to return what the function returned, or every decorated function gives back None.
Show solutionHide solution
def benchmark(func):
"""
A decorator that prints the time a function takes to execute.
"""
def wrapper(*args, **kwargs):
t = time.time()
res = func(*args, **kwargs)
print(func.__name__, time.time() - t)
return res
return wrapper