The measurement problem · Part 2 of 2

timeit Turns the Collector Off, and That Is Worth 2.07x

With the garbage collector disabled the cyclic implementation wins by 4%. With it enabled the same code loses by 2.07x. timeit reports the first number, always.

Elliot Sayer4 min read

timeit is the tool everybody reaches for and the one every warning is attached to. The warnings tend to be about the statistic — best of five is not what your users get — and that turns out to be the smallest of the distortions it introduces. The largest one is not a statistical choice at all. It is a line in the method body.

>>> import inspect, timeit
>>> print(inspect.getsource(timeit.Timer.timeit))

Inside Timer.timeit, before the loop runs: gcold = gc.isenabled() and then gc.disable(). Unconditionally, with no argument to turn it off. Every number timeit has ever reported was taken with the cycle collector switched off.

What the collector is worth

Two implementations of the same job. Both allocate 120,000 objects; one leaves them in reference cycles the counter cannot free, the other does not:

$ python3 experiments/evalloop/timeitmethod.py
python 3.13.2 on darwin
best of 9 everywhere unless the column says otherwise

what turning the collector off is worth

workload                   gc disabled    gc enabled    ratio
cyclic garbage                  5.3 ms       11.0 ms    2.07x
no cycles                       5.5 ms        5.4 ms    0.99x

  timeit.Timer.timeit calls gc.disable() before the loop and restores it after,
  so every number it reports is from the left column.

which statistic the tools hand back

  within one process, 9 rounds
    best                   627.0 ns   what the CLI prints
    median                 630.6 ns
    worst                  631.5 ns
    spread                  1.01x
  across 9 processes, each reporting its own best
    best                   618.4 ns
    median                 623.9 ns
    worst                  635.2 ns
    spread                  1.03x

the shape the loop leaves the call site in

  four objects, one class         9.21 ns a read
  four objects, four classes     13.34 ns a read
  polymorphic costs               1.45x

Read the first block as a comparison rather than as two numbers. With the collector off — which is the only column timeit can produce — the cyclic implementation is the faster of the two, 5.3 ms against 5.5. With the collector on, it is 11.0 against 5.4, which is 2.07x slower.

The ranking inverts. Not the margin, the winner. And the workload that inverts it is not exotic: two objects that point at each other is what a parent-child relationship, a doubly linked list, a cached back-reference and most ORM row objects look like in memory.

The second workload is the control. It allocates the same number of objects and makes no cycles, and the collector costs it nothing measurable — 5.5 against 5.4, inside the noise. So the effect is not “the collector is slow”, it is “the collector charges for cycles”, and timeit never charges for them.

The shape the loop leaves behind

The third block is the second distortion. A timeit loop executes one statement over the same objects several million times, which is precisely the condition the specialising interpreter is built for: an instruction that keeps seeing one class gets rewritten into a variant that assumes that class. Which variant a read gets is visible in the disassembly, and it is not the instruction the compiler emitted.

Four objects of one class, read in a loop, cost 9.21 ns a read. Four objects of four classes, same loop, same attribute, cost 13.34 — 1.45x. Nothing about the attribute changed; the call site stopped being able to assume.

A benchmark of two implementations is usually written with one concrete class each, so both sides get the specialised path. Production code that dispatches over a base class, or over anything with subclasses, gets the other one. The ratio between the two implementations may survive that, and it may not — the point is that timeit cannot tell you, because it only ever runs the left-hand case.

The distortion that was not there

The statistic block is the one that did not produce a finding, and that is worth publishing too. Best, median and worst inside one process spanned 1%. Nine separate processes, each reporting its own best, spanned 3%.

At that size the choice between best and mean does not change a decision. Whatever is wrong with a timeit comparison on this machine, it is not the statistic — and the effort spent arguing about which one to quote would be better spent on the two blocks above it.

That number belongs to this machine on this day: idle, on mains power, nothing else running. On a shared runner it is the first thing that grows. The way to know is to run the harness there.

The method this leaves

Three checks before a timeit result is worth publishing. They are the same three a profile needs, for the same reason: an instrument with a fixed per-call cost is only safe on calls large enough to absorb it.

Does the workload create reference cycles? If it might, time it with perf_counter and the collector in the state the real program has, calling gc.collect() between rounds so each one starts level.

Does the call site see one type in the benchmark and several in production? If so, the benchmark is measuring the specialised path and the program is not.

And say which statistic the number is. Not because the choice matters much — the block above says it did not here — but because a number without that label cannot be compared with anyone else’s.

None of this makes timeit the wrong tool. It makes it a tool with a domain: two implementations of the same shape, allocating nothing that participates in a cycle, called through a site that sees one type in production as well as in the loop. Inside that domain its numbers are as good as its reputation. The failure is not the tool reporting the wrong number; it is a reader taking a number from inside that domain and using it outside.

Where to stop

One machine, macOS on Apple silicon, CPython 3.13.2, idle. Every figure is the best of nine rounds, and the across-process block is nine separate interpreters.

The collector figure is for a workload built to make cycles at a high rate. A program that creates a cycle occasionally will see a smaller number, and one that never creates one will see the control row: no difference at all. Nothing here measures generational thresholds or what gc.freeze does to any of it.

Frequently asked

Should I stop using timeit?

No. Use it for what it is good at, which is comparing two implementations of the same shape that allocate nothing interesting. The two cases to check first are whether the workload creates reference cycles and whether the call site sees more than one type in production. If neither is true, the timeit number and the real number agree.

How do I keep the collector on?

Do not use timeit for that measurement. There is no argument for it — the disable call is unconditional inside Timer.timeit. Time the workload with perf_counter around it, call gc.collect() before each round so the state is the same, and leave the collector in whatever state the calling program would have.

Why does the monomorphic loop measure something different?

Because the interpreter specialises the instruction to the shape it keeps seeing. A LOAD_ATTR that has only ever seen one class becomes a variant that assumes that class; one that sees four falls back to the generic instruction. A timeit loop over one type reaches a state that a call site handling four subclasses never reaches.

Is the 3% spread a property of timeit?

No, it is a property of this machine on the day. It was idle, on mains power, with nothing else running. On a loaded machine or a shared runner the spread is the number that grows, and the way to find out is to run the same harness there rather than to assume either result.

Where this came from

Run it yourself — every figure above came out of these:

  1. evalloop/timeitmethod.py — What timeit's gc.disable() is worth, and the shape its loop leaves
Share

Arrow keys to move, Enter to open.