Skip to content

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).

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 1Read the clock before the call and again after it; the difference is the duration.
Hint 2try: ... finally: ... runs the finally block whether the call returns or raises.
Hint 3from time import perf_counter would keep the real clock even after the tests swap time.perf_counter.

Learn the concepts

More Python problems

All Python problems