Sub topic 2
Timing snippets with perf_counter and timeit
This chapter assumes you can write and run Python functions and loops, and that you know the basics of lists, dicts, and sets. You will learn two standard ways to time small pieces of code and the mistakes that make timings misleading.
Why a single timing is not enough
A stopwatch reading from one run of a snippet is noisy. Other processes compete for the CPU, caches start cold, and the interpreter may be doing background work. A trustworthy number comes from repeating the measurement and looking at the best result.
Timing with time.perf_counter
time.perf_counter() returns a high-resolution clock value in seconds. Only the difference between two calls is meaningful. Use it when you want to time a block of your own code, such as one function call in a larger script.
import time
def build_squares(n):
return [i * i for i in range(n)]
start = time.perf_counter()
build_squares(1_000_000)
elapsed = time.perf_counter() - start
print(f"build_squares took {elapsed:.4f}s")Do not use time.time() for this. It follows the system clock, which can be adjusted while your code runs, and its resolution can be coarser.
perf_counter measures wall-clock time. That includes time spent waiting on disk, the network, or other processes. If you want only the CPU time your process used, time.process_time() is the alternative.
Timing with timeit
timeit runs a snippet many times in a loop and reports the total. It disables garbage collection during the run by default, which removes one source of noise. Use it to compare small alternatives.
import timeit
items_list = list(range(10_000))
items_set = set(items_list)
list_time = timeit.timeit("9_999 in items_list", globals=globals(), number=1_000)
set_time = timeit.timeit("9_999 in items_set", globals=globals(), number=1_000)
print(f"list membership: {list_time:.4f}s")
print(f"set membership: {set_time:.4f}s")The number argument is how many times the snippet runs, and the returned value is the total time for all those runs. The globals=globals() argument lets the snippet see your variables. Without it, the snippet raises a NameError.
The list test scans up to 10,000 items, while the set test is a hash lookup. The set result should be far smaller.
Taking the minimum of several repeats
timeit.repeat runs the whole measurement several times and returns a list of totals. Take the minimum. Higher values are usually caused by interference from other activity, not by your code being slower.
import timeit
times = timeit.repeat(
"sorted(data)",
setup="import random; data = [random.random() for _ in range(10_000)]",
repeat=5,
number=100,
)
print(f"best of 5: {min(times) / 100 * 1000:.3f} ms per call")The setup string runs once per repeat and is not timed. Dividing by number converts the total into a per-call figure.
The command line offers the same tool and picks number for you:
python -m timeit -s "data = list(range(1000))" "sum(data)"Common errors
- Timing setup work. Building test data inside the timed snippet inflates the result. Put it in
setup. - Timing a result that gets cached. If the function memoizes, the first call is slow and later calls are instant. Decide which one you mean to measure.
- Using tiny inputs. A difference between algorithms often appears only on large inputs, as the set example shows.
- Trusting one run. Use
repeatand take the minimum. - Comparing across machines or loads. Compare timings only from the same machine under similar conditions.
Exercise
You run timeit.repeat with repeat=5 and number=100 and get five totals. Which value do you report, and how do you get the time for one call?
Show answer
Report the minimum of the five totals, because larger values mostly reflect interference from other activity. Divide that minimum by number (100) to get the time per call.
Exercise
Your timeit call raises NameError for a list you defined in your script. What argument fixes it?
Show answer
Pass globals=globals() to timeit.timeit so the snippet can see the variables defined in your module.