PythiloLesson 6 of 15 · progress kept in this browser

Timing with timeit

To compare two ways of doing something, time each one many times. A single run is too short to measure and too noisy to trust. timeit runs code in a loop and returns the total seconds.

import timeit

setup = "xs = list(range(1000))"
setup += "; s = set(xs)"
for stmt in ["-1 in xs", "-1 in s"]:
    total = timeit.timeit(
        stmt, setup, number=10_000)
    print(stmt, f"{total:.4f}s")
Your task

Write per_call(func, number, repeat, timer=time.perf_counter) that measures func with timeit.repeat and returns the best time for one call: the smallest measurement divided by number. Pass timer through, so a test can supply its own clock.