Skip to content

Measuring Before Optimising

The Course
•
September 19, 2026
•
9 min read

Today

Every experienced programmer has optimised the wrong thing. The defence isn't intuition — it's a measurement you can repeat, taken on a workload that resembles what your users actually do.

Today is about producing those measurements for the library, and then acting on exactly what they say.

A workload big enough to be measurable

Timing one call tells you almost nothing: at microsecond scale you are mostly measuring the clock, the interpreter warming up, and whatever else the machine is doing.

How noisy a single measurement is Python
import time


def work(items):
    return sum(index * index for index in range(items))


for run in range(3):
    start = time.perf_counter()
    work(100)
    print(f"100 items, run {run}: {(time.perf_counter() - start) * 1e6:8.1f} us")

print()
for run in range(3):
    start = time.perf_counter()
    work(200_000)
    print(f"200k items, run {run}: {(time.perf_counter() - start) * 1e3:8.2f} ms")

The small runs vary by large factors between identical calls. The big ones agree to a few percent. That ratio — noise to signal — is the only reason to prefer a big workload; it isn't about being realistic, it's about being readable.

time.perf_counter() is the right clock: monotonic and the highest resolution available. Never use time.time() for durations — it can jump backwards when the system clock is adjusted.

timeit for the small stuff

For a single expression, timeit handles repetition and picks the best of several runs: python -m timeit -s "setup" "expression". Best-of is deliberate — you want the least-interrupted run, not the average, because interruptions only ever add time.

Reading a profile

cProfile records every call. Run it over the whole benchmark and you profile everything — the setup, and both the no-latency and latency runs:

Shell
python -m cProfile -s tottime benchmark.py

That's rarely what you want. To profile one path in isolation — here, loading 2000 rows one at a time, with no latency and the setup excluded — profile just that call:

Shell
python -c "import benchmark, cProfile; \
           c = benchmark.connect(); ids = benchmark.fill(c); \
           benchmark.Post._instances.clear(); \
           cProfile.run('benchmark.one_by_one(c, ids)', sort='tottime')"

Its output, trimmed to the first few rows (line numbers are from an earlier day's models.py; yours will differ):

Text
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     2000    0.002    0.000    0.010    0.000 models.py:97(get)
     2000    0.001    0.000    0.001    0.000 {method 'execute' of 'sqlite3.Connection' objects}
     2000    0.001    0.000    0.001    0.000 models.py:87(_remember)
     2000    0.001    0.000    0.004    0.000 models.py:43(__init__)
     2000    0.001    0.000    0.001    0.000 {method 'fetchone' of 'sqlite3.Cursor' objects}
     2000    0.001    0.000    0.001    0.000 fields.py:71(check)
     4000    0.001    0.000    0.003    0.000 fields.py:42(__set__)
     2000    0.001    0.000    0.001    0.000 fields.py:89(check)

Four columns matter:

  • ncalls — how many times. Often the most informative number on the page: __set__ runs 4000 times because each of 2000 posts has two fields.
  • tottime — time in that function excluding what it called. Sort by this to find where the CPU actually goes.
  • cumtime — time including callees. Sort by this to find which high-level operation is expensive.
  • percall — the same, divided by ncalls.

Read the profile above and there is no smoking gun: no single line dominates, and the work is spread evenly across query, construction and validation. That is a genuine and common result, and it means "make the code faster" is the wrong question. The right one is "why are we doing this 2000 times?"

The profiler changes what it measures

cProfile adds overhead to every call, so function-call-heavy code looks relatively worse under it than in production. Use it to find where the time goes; use plain timing to decide whether a change actually helped.

Counters beat clocks for tests

Wall-clock assertions in a test suite are a menace: they pass on your laptop and fail on a busy CI machine, and people learn to ignore them.

Count the operation instead. For a data library, the number of queries is both the thing that matters and perfectly deterministic:

Python
class CountingConnection:
    def __init__(self, connection):
        self.real = connection
        self.queries: list[str] = []

    def execute(self, sql, parameters=(), /):
        self.queries.append(sql)
        return self.real.execute(sql, parameters)

That's the whole trick, and it works because of Day 3: Connection is a protocol, so anything with execute and commit can stand in for the real thing.

Python
    def test_get_many_costs_one_query(self) -> None:
        Post.get_many(self.connection, list(range(1, 11)))
        self.assertEqual(self.connection.selects, 1)

That test fails the day someone reintroduces a query per row — on any machine, at any load, in milliseconds.

Exercise

Count the work, not the time

summarise ranks records by views and is accidentally quadratic: it re-scans every record for every record. You'll catch that the way CountingConnection caught extra queries, by counting from outside the code under test.

  1. Write Views: a views count that compares like a number and adds one to a shared Counter every time it's compared. make builds test records with Views in them, so every comparison summarise makes is counted, including the ones hidden inside library calls.
  2. Run the tests. The growth test should now fail, because 10 times the records costs 100 times the comparisons.
  3. Fix summarise: sort once, then look ranks up, so the growth test passes.

Done looks like four passing tests, and a printed line with the two counts.

import random
import sys
import unittest


class Counter:
    def __init__(self):
        self.comparisons = 0


class Views:
    """A views count that adds one to `counter.comparisons` per comparison.

    TODO: keep the value and the counter. Make `<` and `>` compare the values
    and count each comparison. Equal values must also be equal (`==`) and
    hash the same, so a Views works as a dictionary key.
    """

    def __init__(self, value, counter):
        raise NotImplementedError("your code here")


def summarise(records):
    """Return (name, rank) for each record, where rank is 1 + how many records
    have more views. Currently O(n^2): it re-scans for every record."""
    result = []
    for record in records:
        rank = 1
        for other in records:
            if other["views"] > record["views"]:
                rank += 1
        result.append((record["name"], rank))
    return result


def make(count, counter):
    """`count` records in a shuffled order, each with counted views."""
    records = [{"name": f"post {index}", "views": Views(index, counter)}
               for index in range(count)]
    random.Random(0).shuffle(records)
    return records


class Summaries(unittest.TestCase):
    def test_views_count_their_comparisons(self):
        counter = Counter()
        low, high = Views(1, counter), Views(2, counter)
        self.assertTrue(low < high)
        self.assertTrue(high > low)
        self.assertEqual(counter.comparisons, 2)

    def test_it_ranks_correctly(self):
        records = [{"name": "a", "views": 5}, {"name": "b", "views": 9},
                   {"name": "c", "views": 1}]
        self.assertEqual(sorted(summarise(records)), [("a", 2), ("b", 1), ("c", 3)])

    def test_ties_share_a_rank(self):
        records = [{"name": "a", "views": 5}, {"name": "b", "views": 5}]
        self.assertEqual(sorted(summarise(records)), [("a", 1), ("b", 1)])

    def test_the_work_grows_with_the_input_not_its_square(self):
        small, large = Counter(), Counter()
        summarise(make(50, small))
        summarise(make(500, large))
        print(f"\n50 records: {small.comparisons} comparisons; "
              f"500 records: {large.comparisons}")
        # 10x the input: about 16x the work for n log n, 100x for n squared.
        self.assertLess(large.comparisons, small.comparisons * 30)


unittest.TextTestRunner(stream=sys.stdout, verbosity=2).run(
    unittest.defaultTestLoader.loadTestsFromTestCase(Summaries)
)
Hint 1: the idea

Views is a wrapper, like CountingConnection: it holds the real value, does the real comparison, and counts on the way through. Python calls __lt__ for < and __gt__ for >, so those two methods are where the counting goes. For the fix: instead of comparing every record with every other, sort once, give each distinct number of views the rank of its first position, then look ranks up.

Hint 2: a first step

Write Views.__init__ and __lt__ only, and run the tests. The error that follows names the next method Python needed, so let the failures lead you through the rest of Views. Fix summarise only once the growth test fails on its comparison count, rather than on a missing method.

Show one solution
Python
class Views:
    """A views count that adds one to `counter.comparisons` per comparison."""

    def __init__(self, value, counter):
        self.value = value
        self.counter = counter

    def __lt__(self, other):
        self.counter.comparisons += 1
        return self.value < other.value

    def __gt__(self, other):
        self.counter.comparisons += 1
        return self.value > other.value

    def __eq__(self, other):
        return self.value == other.value

    def __hash__(self):
        return hash(self.value)


def summarise(records):
    ordered = sorted(records, key=lambda record: record["views"], reverse=True)
    rank_by_views = {}
    for position, record in enumerate(ordered, start=1):
        rank_by_views.setdefault(record["views"], position)
    return [(record["name"], rank_by_views[record["views"]]) for record in records]

The counter now lives in the data, not in summarise, so summarise can't forget to count, and it can't hide work from it either. Every < that sorted does inside is counted, just like every > in the old nested loop. On these inputs the old version makes 2,500 comparisons for 50 records and 250,000 for 500: ten times the input, a hundred times the work. The new one makes 225 and 3,812, about 17 times, which is what n log n looks like.

The records are shuffled on purpose. Python's sort is close to linear on input that's already in order, so sorted test data would make any version look better than its worst case.

assertLess(large, small * 30) is a shape assertion: it doesn't care about the exact numbers, only that the work grows like n log n and not like n². It fails loudly the day someone brings the nested scan back.

Compare that with a counter that summarise increments itself. That one only counts what its author chose to count: a new nested loop without a counter.count() call would slip past it, and so would anything inside sorted. Counting from outside, through the objects the code has to touch, is the same idea as CountingConnection: measure at a boundary the code under test can't go around.

What you learned

  • Small measurements are mostly noise; size the workload until repeated runs agree.
  • perf_counter for durations, timeit for expressions, cProfile for where the time goes — sorted by tottime for hot code, cumtime for expensive operations.
  • ncalls often answers the question before the timings do.
  • Tests should assert on counts, not seconds.
Last updated on September 19, 2026

Was this article helpful?

Your response is saved on this device.