Lab: Timing Growth Curves with timeit
Measure growth with timeit.autorange and repeat, skip infeasible sizes with a forecast guard, explain why single doubling ratios deviate from the prediction, find the small-n crossover between insertion and merge sort, and verify amortized linear writes with pytest and Hypothesis.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: measure the quadratic ratio with a forecast guard
- Step 2: predict, then test the linear prediction from 10^3 to 10^6
- Step 3: predict, then measure the small-n crossover
- Step 4: separate growth measurement from correctness tests
- Check your understanding
- Apply it
- Review prompt
Lessons of Complexity Analysis
- Counting Steps Instead of Seconds Concept · 20 min
- Reading Loops: From Code to a Bound Worked example · 25 min
- Worst Case, Average Case and Amortized Cost Concept · 20 min
- Budgeting Operations from Input Limits Worked example · 15 min
- Lab: Timing Growth Curves with timeit Lab · 30 min
- Check: Predict, Then Measure Knowledge check · 8 questions
What you will learn
- Distinguish best, worst, average and amortized cost, and explain why appending to a dynamic array is amortized O(1).
- Benchmark two implementations across growing inputs with timeit and explain whether the measurements match the asymptotic prediction.
Prerequisites: Python Foundations
01. Goal and setup
Asymptotic analysis predicts how runtime scales, not exact microseconds. This lab tests three predictions against real measurements: (1) doubling n should multiply an O(n^2) function's time by about 4 and an O(n) function's time by about 2; (2) constant factors let an O(n^2) algorithm beat an O(n log n) one below a small-n crossover; and (3) a doubling dynamic array never exceeds 3n element writes across n appends. The quadratic ratio holds well, but single doublings of the linear function miss 2 by a wide margin, and working out why is the core of this lab.
Why naive timing misleads: reading time.time() around a single call mostly measures scheduler jitter and timer granularity, and building the input inside the timed code adds O(n) list allocation to every call.
Environment: Python 3.12.13, pytest 9.2.0 and hypothesis 6.170.17 in a venv on an Intel i7-3770 Linux desktop. The lab relies on four documented timeit behaviours: Timer.autorange() raises the loop count (1, 2, 5, 10, 20, 50, ...) until one run lasts at least 0.2 seconds; repeat() returns one total per repeat; timing turns garbage collection off; and the docs recommend the min() of the repeats, since higher readings usually come from other processes, followed by a common-sense look at the whole list.
mkdir complexity-lab && cd complexity-lab
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install pytest hypothesis02. Step 1: measure the quadratic ratio with a forecast guard
Create bench_growth.py with two duplicate detectors: has_duplicate_pairs, the O(n^2) pairwise idea behind count_steps_distinct in Counting Steps Instead of Seconds, and has_duplicate_set, an O(n) single pass with a set. Notice four design choices:
- The input is built in
setup=..., so building the list is never billed to the algorithm. - Unique elements force the worst case: neither function can exit early on
list(range(n)). per_callsizes each repeat:autorange()picksnumberso one repeat lasts at least 0.2 s, far above timer resolution, and dividing bynumbergives seconds per call. It returns the best value and all five samples, so you can keep the raw data.- The guard forecasts before it spends: before each new size,
bench_quadraticmultiplies the last time by 4, the ratio your hypothesis predicts, and skips the size if the forecast exceeds the 0.5 s budget. The hypothesis tells you what the next run will cost before you pay for it.
One caveat from the timeit docs: because timing switches garbage collection off, a benchmark of code that builds objects with reference cycles leaves out the collector's pauses; the docs suggest making gc.enable() the first statement in setup when that matters. Integer lists form no cycles, so this lab keeps the default.
import math
import random
import sys
import timeit
from dataclasses import dataclass, field
def has_duplicate_pairs(nums: list[int]) -> bool:
n = len(nums)
for i in range(n):
for j in range(i + 1, n):
if nums[i] == nums[j]:
return True
return False
def has_duplicate_set(nums: list[int]) -> bool:
seen: set[int] = set()
for x in nums:
if x in seen:
return True
seen.add(x)
return False
def per_call(stmt: str, setup: str) -> tuple[float, list[float]]:
"""Return (best seconds per call, all five per-call samples)."""
timer = timeit.Timer(stmt, setup=setup, globals=globals())
number, _ = timer.autorange() # loops per repeat, so one repeat lasts >= 0.2 s
samples = [t / number for t in timer.repeat(repeat=5, number=number)]
return min(samples), samples
def bench_quadratic(budget_s: float = 0.5) -> None:
print("== has_duplicate_pairs (predicted O(n^2)) ==")
prev = 0.0
for n in (500, 1_000, 2_000, 4_000, 8_000, 16_000):
if prev and prev * 4 > budget_s:
print(f"skip n={n}: forecast {prev * 4:.2f} s/call > budget {budget_s} s")
break
best, _ = per_call("has_duplicate_pairs(d)", f"d = list(range({n}))")
ratio = f"{best / prev:.2f}x" if prev else "-"
print(f"n={n:<6} {best * 1e3:8.2f} ms ratio={ratio:>5} "
f"ns per n^2={best / n**2 * 1e9:5.1f}")
prev = bestpython -c "import bench_growth as b; b.bench_quadratic()"== has_duplicate_pairs (predicted O(n^2)) ==
n=500 4.45 ms ratio= - ns per n^2= 17.8
n=1000 19.64 ms ratio=4.41x ns per n^2= 19.6
n=2000 78.29 ms ratio=3.99x ns per n^2= 19.6
n=4000 309.73 ms ratio=3.96x ns per n^2= 19.4
skip n=8000: forecast 1.24 s/call > budget 0.5 sEach doubling multiplied the time by about 4, and the guard skipped n = 8,000 without running it. The last column, time divided by n^2, stayed near 20 ns: when a prediction f(n) is right, time divided by f(n) stays roughly flat, whatever pair of sizes you compare.
03. Step 2: predict, then test the linear prediction from 10^3 to 10^6
Predict before running: has_duplicate_set does constant work per item, so write down the ratio you expect each time n doubles or grows tenfold. Then append part 2 and run bench_linear. It also prints the log-log slope between the smallest and largest size: the exponent k for which n^k matches how the time grew (1 for linear, 2 for quadratic).
def bench_linear() -> None:
print("== has_duplicate_set (predicted O(n)) ==")
sizes = (1_000, 2_000, 4_000, 10_000, 100_000, 1_000_000)
times: list[float] = []
for i, n in enumerate(sizes):
best, _ = per_call("has_duplicate_set(d)", f"d = list(range({n}))")
times.append(best)
grow = "-"
if i > 0:
grow = f"x{best / times[i - 1]:.2f} for n x{n / sizes[i - 1]:g}"
print(f"n={n:<9} {best * 1e6:9.1f} us {grow:<16} "
f"ns per item={best / n * 1e9:5.1f}")
slope = math.log(times[-1] / times[0]) / math.log(sizes[-1] / sizes[0])
print(f"log-log slope from 10^3 to 10^6: {slope:.2f} (1.00 = linear)")
def show_set_resizes(limit: int = 5_000) -> None:
seen: set[int] = set()
size = sys.getsizeof(seen)
for x in range(limit):
seen.add(x)
if sys.getsizeof(seen) != size:
size = sys.getsizeof(seen)
print(f"after {len(seen):>4} adds: sys.getsizeof(seen) = {size:>7,} bytes")
def bench_one_more_item() -> None:
for n in (1_228, 1_229):
best, _ = per_call("has_duplicate_set(d)", f"d = list(range({n}))")
print(f"n={n}: {best * 1e6:6.1f} us per call")python -c "import bench_growth as b; b.bench_linear()"== has_duplicate_set (predicted O(n)) ==
n=1000 49.7 us - ns per item= 49.7
n=2000 127.0 us x2.56 for n x2 ns per item= 63.5
n=4000 215.6 us x1.70 for n x2 ns per item= 53.9
n=10000 486.6 us x2.26 for n x2.5 ns per item= 48.7
n=100000 5846.2 us x12.02 for n x10 ns per item= 58.5
n=1000000 71792.4 us x12.28 for n x10 ns per item= 71.8
log-log slope from 10^3 to 10^6: 1.05 (1.00 = linear)In our run the first doubling gave x2.56, the next only x1.70, and the last tenfold step x12.28; a second run gave x2.66, x1.83 and x13.33. Yet the slope came out at 1.05 and 1.06. The function is linear; single ratios mislead because the step-counting model leaves out four effects.
Step costs inside the data structure. A set does not grow smoothly: whenever its table is about 60% full, it moves every item into a larger table. Run python -c "import bench_growth as b; b.show_set_resizes()" to see where that happens:
after 5 adds: sys.getsizeof(seen) = 728 bytes
after 19 adds: sys.getsizeof(seen) = 2,264 bytes
after 77 adds: sys.getsizeof(seen) = 8,408 bytes
after 307 adds: sys.getsizeof(seen) = 32,984 bytes
after 1229 adds: sys.getsizeof(seen) = 131,288 bytes
after 4915 adds: sys.getsizeof(seen) = 524,504 bytesNow predict how much longer a call takes at n = 1,229 than at n = 1,228; one more item ought to cost about 50 ns. Run python -c "import bench_growth as b; b.bench_one_more_item()":
n=1228: 55.7 us per call
n=1229: 93.8 us per callOne more item triggers the move into a 131 KB table, paid on every call: 24 to 42 µs in our 20 logged runs, 4 to 16 µs in a reviewer's 10 runs on this machine, depending on the allocator's state (the slow runs showed about 10 page faults per call). That fixed cost is missing at n = 1,000, large at n = 2,000, and spread over twice as many items at n = 4,000, so one doubling reads high, the next low. The table sizes grow geometrically, so the total stays O(n), as in Worst Case, Average Case and Amortized Cost.
Memory caches. At large n the set and the integers outgrow the CPU caches (8 MB of L3 here), so each lookup waits longer for memory: time per item rose from about 55 ns at 10^5 to about 72 ns at 10^6. We could not read hardware cache counters on this machine, so this is the likely cause, not a proven one.
Fixed per-call cost. Calling the function and creating the empty set cost the same at every n: negligible from 10^3 up, but from n = 5 to n = 10 the time grew only about 1.5 times on our machine.
Noise and warm-up. Other processes, CPU frequency changes and first runs on cold caches add scatter; long repeats and min() reduce it, and the five samples show how much is left.
The practical rule: judge growth over a wide span (tenfold or more), from the slope, or from a flat time / f(n) column, not from one doubling. That shape tends to carry over to another machine; the ratio of any single step does not.
04. Step 3: predict, then measure the small-n crossover
Predict before running: compare pure-Python insertion_sort_copy (O(n^2)) with recursive merge_sort_copy (O(n log n), slicing sublists and allocating a fresh merged list at every call) for n = 5, 10, 20, 50, 100, 500 on seeded random integers. Write down where you expect merge sort to overtake, then append part 3 and run bench_crossover.
def insertion_sort_copy(nums: list[int]) -> list[int]:
out = nums[:]
for i in range(1, len(out)):
key = out[i]
j = i - 1
while j >= 0 and out[j] > key:
out[j + 1] = out[j]
j -= 1
out[j + 1] = key
return out
def merge_sort_copy(nums: list[int]) -> list[int]:
if len(nums) <= 1:
return nums[:]
mid = len(nums) // 2
left = merge_sort_copy(nums[:mid])
right = merge_sort_copy(nums[mid:])
merged: list[int] = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i]); i += 1
else:
merged.append(right[j]); j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged
def bench_crossover() -> None:
print("== Small-n crossover (best of 5 repeats, seed=42) ==")
rng = random.Random(42)
for n in (5, 10, 20, 50, 100, 500):
sample = [rng.randint(0, 10_000) for _ in range(n)]
ti, _ = per_call("insertion_sort_copy(d)", f"d = {sample!r}")
tm, _ = per_call("merge_sort_copy(d)", f"d = {sample!r}")
winner = "insertion" if ti < tm else "merge"
print(f"n={n:<4} insertion={ti * 1e6:8.2f}us "
f"merge={tm * 1e6:8.2f}us winner={winner}")python -c "import bench_growth as b; b.bench_crossover()"== Small-n crossover (best of 5 repeats, seed=42) ==
n=5 insertion= 0.77us merge= 3.49us winner=insertion
n=10 insertion= 2.63us merge= 8.56us winner=insertion
n=20 insertion= 8.86us merge= 20.02us winner=insertion
n=50 insertion= 40.74us merge= 58.62us winner=insertion
n=100 insertion= 154.28us merge= 133.46us winner=merge
n=500 insertion= 4000.84us merge= 755.96us winner=mergeIn our run, insertion sort won through n = 50 (40.74us vs 58.62us), because recursive calls and slice allocations carry heavy constant overhead at small n. By n = 100 merge sort had crossed over (133.46us vs 154.28us), and at n = 500 it needed about a fifth of the time. This is also why CPython's list sort builds short runs with binary insertion sort and sorts any list of fewer than 64 items that way (see Objects/listsort.txt).
Simplification boundary: exact numbers depend on CPU, load and Python version, hence the illustrative captions. Near the crossover, close timings can even swap between runs: an earlier version of this lab, with shorter repeats on a busier machine, once saw merge sort win at n = 50 and lose at n = 100. What carries over is that a small-n crossover exists, not its exact position.
05. Step 4: separate growth measurement from correctness tests
Timings are noisy; a correctness or step-bound invariant is deterministic, and a fast benchmark proves nothing about edge cases. Append part 4 (DoublingArray, doubling_demo and a __main__ block that runs every step), create test_complexity.py (building on Type Hints and Tests with pytest), and check two invariants across hundreds of generated lists: DoublingArray matches a list while writing at most 3 * len(items) times, and the two detectors agree, including on empty lists and negative numbers.
@dataclass
class DoublingArray:
_buf: list[int | None] = field(default_factory=lambda: [None])
_len: int = 0
total_writes: int = 0
def append(self, value: int) -> None:
if self._len == len(self._buf):
new_buf: list[int | None] = [None] * (len(self._buf) * 2)
for i in range(self._len):
new_buf[i] = self._buf[i]
self.total_writes += 1
self._buf = new_buf
self._buf[self._len] = value
self._len += 1
self.total_writes += 1
def to_list(self) -> list[int]:
return [x for x in self._buf[: self._len] if x is not None]
def doubling_demo() -> None:
arr = DoublingArray()
for x in range(1_000):
arr.append(x)
print(f"DoublingArray(1000): writes={arr.total_writes}, cap={len(arr._buf)}")
if __name__ == "__main__":
bench_quadratic()
bench_linear()
show_set_resizes()
bench_crossover()
doubling_demo()from hypothesis import given
from hypothesis import strategies as st
from bench_growth import DoublingArray, has_duplicate_pairs, has_duplicate_set
@given(st.lists(st.integers(), max_size=200))
def test_doubling_array_matches_list_and_stays_linear(items: list[int]) -> None:
arr = DoublingArray()
for x in items:
arr.append(x)
assert arr.to_list() == items
assert arr.total_writes <= 3 * len(items)
@given(st.lists(st.integers(min_value=-50, max_value=50), max_size=80))
def test_duplicate_detectors_agree(items: list[int]) -> None:
assert has_duplicate_pairs(items) == has_duplicate_set(items)python -c "import bench_growth as b; b.doubling_demo()"
pytest -v test_complexity.pyDoublingArray(1000): writes=2023, cap=1024
test_complexity.py::test_doubling_array_matches_list_and_stays_linear PASSED [ 50%]
test_complexity.py::test_duplicate_detectors_agree PASSED [100%]06. Check your understanding
07. Apply it
Complete the skill practice brief: write six short Python functions of distinct complexity classes (including O(1), O(log n), O(n), O(n log n), O(n^2), and O(n + m^2)) with the predicted time and auxiliary space of each, then benchmark two of them from n = 10^3 to n = 10^6 with per_call and a forecast guard on a fixed budget. Save the five raw samples of every size to a CSV file, report the slope as well as the single ratios, explain which of this lab's four effects accounts for any gap, and keep correctness checks in pytest, separate from the timing script.
Next, apply these costs to real containers in Arrays & Strings and Hashing & Hash Tables.
08. Review prompt
Without looking back:
- Why do the
timeitdocs recommendmin()over the arithmetic mean oftimeit.repeat, and what should you still look at afterwards? - Name two reasons why a single doubling of an
O(n)function can givex2.6orx1.7, and say what you would measure instead. - Why did
insertion_sort_copybeatmerge_sort_copyatn = 20even thoughO(n log n)beatsO(n^2)asymptotically?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.