Skip to content
Tactiverge

School/○ Innovator/Week 6

Module check: measure growth, then explain it

Your model says the planner is O(n). The stopwatch says doubling the map quadruples the time. Who's right?

About 45 min · 3 goals · Checked by automated tests

1.Why should I care?

Big-O is a prediction; timings are evidence. Good engineers measure to check the prediction, and when they disagree, they find out why. This module check brings weeks 4–6 together in one honest experiment.

  • ◇ Time code fairly: repeat runs, report the best or median, and keep everything else fixed.
  • ◇ Estimate a growth rate from the ratio of times when n doubles.
  • ◇ Explain what big-O does not tell you: constants, small inputs, memory and hardware effects.

2.Predict

You time a function at n = 1,000 (12 ms), 2,000 (47 ms) and 4,000 (190 ms). What growth does this suggest?

Guess first. Being wrong here is how the surprise works.

3.Understand

Fair timing

Use time.perf_counter() or timeit; run each size several times and report the best or the median (the first run is often slow while Python warms up). Change only n. Close other heavy programs. Record the machine and Python version so others can compare.

Read growth from ratios

When the input doubles, the time ratio tells you the growth: about 2 for O(n), a bit over 2 for O(n log n), about 4 for O(n²). Plotting time against n on log–log axes turns a power law into a straight line whose slope is the exponent.

What big-O won't tell you

Constants (C code inside Python is far faster than Python loops), memory and caching effects, small-input overheads and noise from other programs. A careful report states the prediction, the measurement and an explanation of any gap.

Explain it another way

Weighing yourself once on a wobbly floor tells you little. Weigh several times, on a firm floor, and look at the trend over weeks.

Worked example 1

Time a list-membership check versus a set at several sizes and estimate the exponent.

import math
import time


def best_time(fn, repeats=5):
    best = float("inf")
    for _ in range(repeats):
        t0 = time.perf_counter()
        fn()
        best = min(best, time.perf_counter() - t0)
    return best


def count_dupes_list(xs):
    seen, dupes = [], 0
    for x in xs:
        if x in seen:          # scans the list: O(len(seen))
            dupes += 1
        else:
            seen.append(x)
    return dupes


def count_dupes_set(xs):
    seen, dupes = set(), 0
    for x in xs:
        if x in seen:          # hash lookup: O(1) on average
            dupes += 1
        else:
            seen.add(x)
    return dupes


sizes = [500, 1000, 2000]
for name, fn in [("list", count_dupes_list), ("set", count_dupes_set)]:
    times = [best_time(lambda n=n: fn(list(range(n)))) for n in sizes]
    p = math.log2(times[2] / times[1])
    print(name, ["%.2e" % t for t in times], "exponent ~", round(p, 1))
# Typical output (exact times vary by machine): list exponent ~2, set exponent ~1

Common mix-ups

  • One timing run is enough.
    ✓ Timings are noisy. Repeat, take the best or median, and use several sizes.
  • If timings disagree with big-O, the timings are wrong.
    ✓ Usually the model is incomplete: look for hidden loops or costs you didn't count.

4.Discover

In the Code Lab, time your visited-as-list BFS and your visited-as-set BFS on open grids of 20 × 20, 40 × 40, 80 × 80 (and 160 × 160 if it's quick). Use the best of five runs. Each step doubles the side, so the number of cells quadruples. What time ratio does each version show per step, and what growth does that suggest?

Can't use the interactive? Read a description instead

The Code Lab experiment can be done from a table: list-based visited checks grow roughly 4 times when the number of cells doubles (quadratic), while set-based visited checks grow roughly 2 times (linear). The worked example's duplicate counter shows the same pattern, with an estimated exponent near 2 for the list and near 1 for the set.

5.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

Practice 1

Times: 30 ms at n = 5,000 and 240 ms at n = 10,000. Estimate the exponent p in T ≈ c·n^p.

6.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

Practice 2

Which timing method is most trustworthy?

Practice 3 · a fresh version every time

Timing tests show a parts-matching script grows like n² and takes 12 ms for n = 1024. Assuming that growth holds, predict its time for n = 4096, in ms.

ms

Practice 4 · a fresh version every time

A program is scanning a sensor log. Its step count is measured with: count = sum(1 for i in range(46) for j in range(i, 46)). What value does count hold?

steps

Practice 5

Big-O predicts O(n), but doubling n multiplies your measured time by 4. What is the best next step?

Practice 6

Which of these does big-O NOT tell you?

7.Apply it

Module check deliverable. A one-page investigation: your BFS with visited as a list and as a set, timed on at least four grid sizes (best of five). Include a table, an estimated exponent for each version, your big-O prediction for each, and a paragraph explaining any disagreement. State your machine and Python version.

8.Reflect

9.Go further

Concepts: Algorithms, searching and complexity · Reproducibility and documentation · Measurement error and uncertainty