Skip to content

Publish dict versus multidict comparison tables - #1532

Merged
asvetlov merged 7 commits into
aio-libs:masterfrom
asvetlov:claude/benchmark-comparison-tables-602331
Sep 23, 2026
Merged

asvetlov merged 7 commits into
aio-libs:masterfrom
asvetlov:claude/benchmark-comparison-tables-602331

Conversation

@asvetlov

Copy link
Copy Markdown
Member

What do these changes do?

docs/benchmark.rst explained how to run the benchmarks but published
no numbers, so the question a reader arrives with, what MultiDict
costs compared with a plain dict, went unanswered, and the
free-threaded build's overhead was undocumented. The page now carries
per-operation tables for dict, MultiDict and CIMultiDict on the
GIL build, the same on the free-threaded build, a free-threading
overhead summary with dict as the control, and a pure-Python backend
table. Fifteen rows, one per operation the two types share.

The numbers are Callgrind instruction counts rather than wall clock,
because they do not depend on scheduling or CPU frequency and so
reproduce on a busy machine; a regression shows up as a changed integer.
benchmarks/callgrind_driver.py measures each cell with four child
processes, two round counts per arm. Differencing two non-zero round
counts cancels interpreter startup, and subtracting an arm with the
operation elided cancels the driving loop, which is worth a few hundred
instructions per iteration and would otherwise compress every ratio
toward 1. benchmarks/render_tables.py turns two runs into the tables
and rewrites the block between markers in the page.

Getting there needed the scripts restructured. The pyperf script built
each benchmark out of exec'd source templates, which left nowhere to
run setup between measured iterations and limited it to six
non-destructive operations. benchmarks/operations.py now holds every
operation as a setup/run/noop triple that all three entry points read,
and the rebuild a destructive operation needs happens in setup, outside
the measured region, so pop(), clear() and del d[key] can be
measured without counting it.

Both backends are covered: the tables carry MultiDict and
CIMultiDict for the C extension and for the pure-Python
implementation, imported directly from multidict._multidict and
multidict._multidict_py, so one install measures both.

AGENTS.md now asks for the tables to be refreshed in the same PR as
any significant performance change, with the commands to do it.

Are there changes in behavior for the user?

No. Nothing outside benchmarks/, docs/ and AGENTS.md is touched.

Is it a substantial burden for the maintainers to support this?

The tables need regenerating when performance moves, which is the point
of them; AGENTS.md documents how. The measurement is deterministic, so
it does not need a quiet machine, but it does need Valgrind and one
virtualenv per interpreter build.

Related issue number

None.

Checklist

  • I think the code is well written
  • Unit tests for the changes exist — N/A, benchmarks/ is not part of the test suite; callgrind_driver.py --self-check exercises every operation on every implementation instead
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt — N/A, no such file in this repo
  • Add a new news fragment into the CHANGES/ folder
  • make doc-spelling passes and any new technical words are added to docs/spelling_wordlist.txt
Agent run details (optional, for reviewers)

Measured on CPython 3.14.7 and 3.14.7t, Valgrind 3.26.0, at dd9c64f.

Verification:

  • python benchmarks/callgrind_driver.py --self-check — 95 cells build,
    run and end in the asserted state.
  • Full collection on both builds, twice, independently: all 75 published
    cells identical, reported drift 0.
  • make doc and make doc-spelling — both pass; Sphinx runs with -W.
  • pre-commit run --files benchmarks/*.py docs/benchmark.rst AGENTS.md ...
    — ruff check, ruff format and both mypy passes clean.
  • benchmark.py --impl multidict_c -o c.json, same for multidict_py,
    then pyperf compare_to — the wall-clock path still produces
    comparable output after the rewrite.

The driver's self-checks earned their place during development: the
bit-exactness check caught ruff format rewriting operations.py while
a collection was in flight, and refused to emit numbers.

Two measurement traps the driver guards against, both of which produce
plausible wrong numbers rather than an error:

  • Handing Valgrind a wrapper script such as a pyenv shim. Valgrind
    defaults to --trace-children=no and detaches at the exec, so it
    reports a constant that never changes with the round count.
  • Leaving PYTHONHASHSEED unset. String hash randomisation changes the
    hash table's probe sequences per process and moved one case by 4.4%,
    which looks exactly like a real regression.

Rebasing this branch onto current master mid-review changed the
CIMultiDict rows substantially, since #1527 landed in between:
d[key] went from 1,092 to 240 instructions, key in d from 1,076 to
226, and cls(items) from 219,466 to 62,942. The published tables are
measured at this branch's base, not the older one.

Drafted with Claude Code (Opus 5); reviewed by @asvetlov.

@pyba-chronographer pyba-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label Sep 23, 2026
Comment thread benchmarks/operations.py Fixed
Comment thread benchmarks/callgrind_driver.py Fixed
@asvetlov
asvetlov marked this pull request as ready for review September 23, 2026 11:23
@asvetlov
asvetlov requested a review from webknjaz as a code owner September 23, 2026 11:23
@codspeed

codspeed Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 12.74%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
✅ 309 untouched benchmarks

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ test_create_multidict_with_dict[ci-c] 99.4 µs 88.1 µs +12.74%

Tip

Curious why performance improved? Comment @codspeedbot explain why performance improved on this PR, or directly use the CodSpeed MCP with your agent.


Comparing asvetlov:claude/benchmark-comparison-tables-602331 (cd62120) with master (fdceefa)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

Safe to merge.

Reviews (3) · Last reviewed commit: "Refuse to publish whole-process instruct..."

Comment thread benchmarks/callgrind_driver.py Resolved
Comment thread benchmarks/callgrind_driver.py Resolved
Comment thread benchmarks/operations.py Resolved
@greptile-apps

This comment has been minimized.

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3e5aa5b) to head (cd62120).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff            @@
##            master     #1532   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           40        40           
  Lines         6820      6820           
  Branches       596       596           
=========================================
  Hits          6820      6820           
Flag Coverage Δ
CI-GHA 100.00% <ø> (ø)
pytest 100.00% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

The pyperf script built each benchmark out of exec'd source templates,
which left no place to run setup between measured iterations; that
limited it to six non-destructive operations.

benchmarks/operations.py now holds every benchmarked operation as a
setup/run/noop triple, and benchmark.py measures it with
bench_time_func.  Rebuilding the mapping happens in setup, outside the
timed region, so pop(), clear() and the rest can be measured without
counting the rebuild.  The noop arm is the same loop with the operation
elided, which lets a consumer subtract the driving loop.

The registry carries the fifteen operations dict also has, plus the
multidict-only ones the old script covered.
docs/benchmark.rst told a contributor how to run the benchmarks but
published no numbers, so the question a reader arrives with, what
MultiDict costs compared with a plain dict, went unanswered, and the
free-threaded build's overhead was undocumented.

The numbers are Callgrind instruction counts rather than wall clock.
They do not depend on scheduling or CPU frequency, so they are
reproducible on a busy machine and a regression shows up as a changed
integer.  callgrind_driver.py measures each cell with four children,
two round counts per arm; differencing two non-zero round counts cancels
interpreter startup and subtracting the noop arm cancels the driving
loop.  It refuses a wrapper script, checks that the counts scale with
the round count, and re-measures one cell to confirm the result is
bit-identical.

render_tables.py turns two runs into the tables, and rewrites the block
between the markers in docs/benchmark.rst.  It refuses to build the
free-threading table when the two runs disagree on the CPython version.

The page also covers preparing a machine for the wall-clock mode, and
AGENTS.md now asks for the tables to be refreshed whenever performance
moves.
Measured on CPython 3.14.7, GIL and free-threaded builds, at dd9c64f.
Every cell reproduces bit for bit across independent runs.
Both words pass a local docs build because those packages happen to be
importable there, and sphinxcontrib-spelling skips anything that names
an importable module.  CI installs only requirements/doc.txt for the
spelling run, where neither is present, so the build failed there.
When pytest-codspeed does not expose the Valgrind client requests the
child cannot turn instrumentation on, yet the driver still started
Valgrind with --instr-atstart=no, so every count came back as zero and
the scaling check aborted the run. Pick the initial instrumentation
state from the child's capability instead, and express the scaling
check as a minimum number of instructions per operation so that it
holds in both modes rather than only where the counted region is
small.

Whole-process counting puts the untimed setup inside the counted
region, which only cancels where both arms leave the mapping in the
same state, so the driver now warns that those numbers are approximate.

Also guard sys._is_gil_enabled(), which does not exist before 3.13, and
say in the docs that the update row replaces existing keys rather than
inserting new ones.
Rebasing picked up the reflist and deferred-decref merge, which takes
2 to 4 percent off both setitem rows on either build, and the update
row is relabelled to say that its keys already exist.
@asvetlov
asvetlov force-pushed the claude/benchmark-comparison-tables-602331 branch from 2d27020 to ba676c3 Compare September 23, 2026 12:07
Comment thread benchmarks/render_tables.py Resolved
Without the Valgrind client requests the untimed setup is counted too,
and it only cancels where both arms leave the mapping in the same
state, so d.clear() reads 51 instructions instead of 4,818. The driver
warns about it; the renderer now declines to put such a run in the
documentation, while still printing it to stdout.
@asvetlov
asvetlov merged commit aa8c8ac into aio-libs:master Sep 23, 2026
62 checks passed
@asvetlov
asvetlov deleted the claude/benchmark-comparison-tables-602331 branch September 23, 2026 18:16
asvetlov added a commit that referenced this pull request Sep 24, 2026
<!-- Thank you for your contribution! -->

## What do these changes do?

On the free-threaded build every lock-free reader that brings
`num_active_readers` back to zero calls `_md_drain_retired()`, which
without a second thread is every single lookup. The first thing that
function does is a sequentially consistent exchange on `md->retired`,
and that list is empty almost every time.

The drain now checks the list with a load first and the rest of it sits
behind a call, so a lookup with nothing to free pays one load instead of
an out-of-line call and a read-modify-write. The load stays sequentially
consistent: a writer that pushes and then reads `num_active_readers` as
nonzero leaves the table for whoever brings that count to zero, so the
reader doing so must not be able to miss the push, and only a seq_cst
load is ordered against the push in the single total order. On x86-64
that is the same plain `mov`, so it is free; the cost being skipped is
the exchange.

Instructions per operation, CPython 3.14.7 free-threaded:

| Operation | Before | After |
| --- | ---: | ---: |
| `key in md` | 283 | 253 (-10.6%) |
| `md[key]` | 317 | 292 (-7.9%) |
| `md.get(key)`, miss | 499 | 474 (-5.0%) |

`CIMultiDict` moves -8.1%, -6.2% and -3.3% on the same three. No other
benchmarked operation changes beyond the measurement's noise floor.
Wall clock improves more than the instruction counts do, because
Callgrind cannot see the removed `lock`-prefixed exchange. Measured back
to back against a build of the merge base, two passes each: `key in md`
35.5/35.3 ns before against 29.0/28.7 after, `md[key]` 37.1/36.9 against
30.9/30.6, so about -18%. `CIMultiDict` moves within the noise of this
machine on wall clock and I would not claim a figure for it.

This is free-threaded only. `atomic_helpers.h` is entirely inside
`#ifdef Py_GIL_DISABLED`, and `tools/codegen_diff.py` reports `0 of 190
functions differ` for the GIL build. It is also C-extension only: the
pure-Python backend has no table retirement to skip.

The second commit regenerates `docs/benchmark.rst`. Those numbers were
last collected on the branch of #1532, so the refresh also absorbs
#1533 through #1538; the free-threaded read rows are the part this
change accounts for.

## Are there changes in behavior for the user?

No, other than free-threaded reads being faster.

## Is it a substantial burden for the maintainers to support this?

No. The retirement protocol is unchanged; one branch is added in front
of it, and the reasoning for why the window is safe is in the comment
above the gate.

## Related issue number

None; found while comparing `multidict` against `dict` on the
operations both have.

## Checklist

- [x] I think the code is well written
- [x] Unit tests for the changes exist
- [x] Documentation reflects the changes
- [ ] If you provide code modification, please add yourself to
`CONTRIBUTORS.txt` — N/A
- [x] Add a new news fragment into the `CHANGES/` folder
- [x] `make doc-spelling` passes and any new technical words are added
to `docs/spelling_wordlist.txt`

On unit tests: no new test is added because the existing
`test_drain_retired_defers_busy_table_thread_safety()` and
`test_setitem_update_thread_safety()` already drive this path from both
sides, forcing a retirement on nearly every insert while lock-free
readers run; they exercise the gate taken and not taken.

Drafted with Claude Opus 5 in Claude Code; reviewed by @asvetlov.

<details>
<summary>Agent run details (optional, for reviewers)</summary>

Three variants were measured before this one was picked. Marking the
slow path `COLD` rather than `NOINLINE` bought the same read win but
cost `d.clear()` 12% and `d.copy()` 4%: `cold` implies optimize-for-size
and `_md_free_retired()`'s per-entry decref loop lives down there.
Adding the gate without moving the body out of line recovered only 1-2%,
which says the out-of-line call, not the exchange, was most of the cost.

Builds: one venv and one tree copy per leg, rebased on 9f28f61.

```
tools/codegen_diff.py --ref 9f28f61
  python3.14    0 of 190 functions differ
  python3.14t  35 of 196 functions differ (_md_drain_retired -> _md_drain_retired_slow
               and its former inline sites)

pytest, 3.14.7 GIL           2353 passed, 107 skipped
pytest, 3.14.7t              2342 passed, 118 skipped
pytest, pure Python          1138 passed, 11 skipped, 1141 deselected
pytest, 3.10.17 (cibw marks) 2260 passed, 21 skipped, 179 deselected
TSan, 3.14.7t-tsan           2331 passed, 0 ThreadSanitizer warnings, 8m30s
ASan+UBSan, 3.14.7 debug     2342 passed, 107 skipped
make doc-spelling            build succeeded
pre-commit (clang-format)    passed
```

Benchmarks are `benchmarks/callgrind_driver.py`, bracketed, `drift_ir
0`,
valgrind 3.26.0, Intel Core Ultra 7 155H.
</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants