Code

Measure First

The golden rule of speed: measure before you optimize. Your guess about which part is slow is often wrong.

time.perf_counter() is a high-resolution clock made for timing code:

import time

start = time.perf_counter()
crunch()
elapsed = time.perf_counter() - start
print(f"{elapsed:.4f}s")

One measurement is noisy, because other programs and the garbage collector can interrupt you. So we repeat it and keep the minimum. Noise only ever adds time, so the fastest run is the most honest.

The timeit module does this for you:

import timeit
timeit.timeit("sum(range(1000))", number=1000)
timeit.repeat(crunch, number=10, repeat=5)  # 5 totals

Assignment

  1. best_time(func, repeats=5): call func() exactly repeats times, timing each call with time.perf_counter(). Return the smallest time in seconds.
  2. faster(f, g): use best_time on both and return the __name__ of the faster function.