Repository navigation
Conversation
Merging this PR will improve performance by 12.74%
|
| 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)
|
This comment has been minimized.
This comment has been minimized.
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
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.
2d27020 to
ba676c3
Compare
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.
<!-- 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>
What do these changes do?
docs/benchmark.rstexplained how to run the benchmarks but publishedno numbers, so the question a reader arrives with, what
MultiDictcosts compared with a plain
dict, went unanswered, and thefree-threaded build's overhead was undocumented. The page now carries
per-operation tables for
dict,MultiDictandCIMultiDicton theGIL build, the same on the free-threaded build, a free-threading
overhead summary with
dictas the control, and a pure-Python backendtable. 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.pymeasures each cell with four childprocesses, 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.pyturns two runs into the tablesand 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 torun setup between measured iterations and limited it to six
non-destructive operations.
benchmarks/operations.pynow holds everyoperation 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()anddel d[key]can bemeasured without counting it.
Both backends are covered: the tables carry
MultiDictandCIMultiDictfor the C extension and for the pure-Pythonimplementation, imported directly from
multidict._multidictandmultidict._multidict_py, so one install measures both.AGENTS.mdnow asks for the tables to be refreshed in the same PR asany significant performance change, with the commands to do it.
Are there changes in behavior for the user?
No. Nothing outside
benchmarks/,docs/andAGENTS.mdis 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.mddocuments how. The measurement is deterministic, soit does not need a quiet machine, but it does need Valgrind and one
virtualenv per interpreter build.
Related issue number
None.
Checklist
benchmarks/is not part of the test suite;callgrind_driver.py --self-checkexercises every operation on every implementation insteadCONTRIBUTORS.txt— N/A, no such file in this repoCHANGES/foldermake doc-spellingpasses and any new technical words are added todocs/spelling_wordlist.txtAgent 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.
cells identical, reported drift 0.
make docandmake 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 formultidict_py,then
pyperf compare_to— the wall-clock path still producescomparable output after the rewrite.
The driver's self-checks earned their place during development: the
bit-exactness check caught
ruff formatrewritingoperations.pywhilea 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:
pyenvshim. Valgrinddefaults to
--trace-children=noand detaches at theexec, so itreports a constant that never changes with the round count.
PYTHONHASHSEEDunset. String hash randomisation changes thehash 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
CIMultiDictrows substantially, since #1527 landed in between:d[key]went from 1,092 to 240 instructions,key in dfrom 1,076 to226, and
cls(items)from 219,466 to 62,942. The published tables aremeasured at this branch's base, not the older one.
Drafted with Claude Code (Opus 5); reviewed by @asvetlov.