18. Time Every Call
Difficulty: Medium · Topic: Functions & decorators
Write a decorator timed that measures how long each call of a function takes and appends the duration, in seconds, to a list on the decorated function (work.timings in the sample).
- Measure with
time.perf_counter(), called astime.perf_counter()each time. The tests replace it with a fake clock. - The function returns what it returned before. If it raises, the exception still reaches the caller, and the call is still timed.
- Each decorated function has its own
timings, and keeps its__name__.
In the sample, the fake clock returns 10.0, 10.5, 20.0 and 23.0 in turn. The first call reads 10.0 before and 10.5 after, so it took 0.5 seconds; the second took 23.0 − 20.0 = 3.0.
Your code runs in CPython on our servers against 4 tests, including hidden ones.
Sample test
import time
ticks = iter([10.0, 10.5, 20.0, 23.0])
time.perf_counter = lambda: next(ticks)
@timed
def work(x):
return x * 2
(work(1), work(2), work.timings)Expected: (2, 4, [0.5, 3.0])
Hints
Hint 1
Read the clock before the call and again after it; the difference is the duration.Hint 2
try: ... finally: ... runs the finally block whether the call returns or raises.Hint 3
from time import perf_counter would keep the real clock even after the tests swap time.perf_counter.Learn the concepts
- Decorators · 8 min read. What @ does, wrappers for any function, functools.wraps, and decorators with arguments.
More Python problems
- Counter with a Closure · Easy
- A Logging Decorator That Keeps Metadata · Easy
- Memoize a Function · Medium
- Retry with Backoff · Hard
- Rate Limiter Decorator · Hard