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")Read the numbers right
numberis how many runs make one measurement. Divide by it to get the time per call.timeit.repeattakes several measurements. Keep the minimum: other work on the machine can only add time, never take it away.- The clock is the
timerargument,time.perf_counterunless you pass another. - Time realistic sizes. On tiny inputs the slower algorithm can win.
On a desktop, python -m timeit "sorted(range(100))" does the same and picks number for you.
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.
The explanation opens here once every check passes.