
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
best_time(func, repeats=5): callfunc()exactlyrepeatstimes, timing each call withtime.perf_counter(). Return the smallest time in seconds.faster(f, g): usebest_timeon both and return the__name__of the faster function.
best_time(func, repeats=5): callfunc()exactlyrepeatstimes, timing each call withtime.perf_counter(). Return the smallest time in seconds.faster(f, g): usebest_timeon both and return the__name__of the faster function.
main.py Python sleeping
Press Run to try your code, then Check to test it.