Speed Demon 2026: Cause Of Death
This book is my Speed Demon 2026 entry, one chapter per track. It’s all Rust with no crates, and every output hashes the same as the reference on every seed I tested. Here’s where each track landed, going by the final code’s best board run on the public dataset (seed 1):
| Track | Reference | Mine | Memory | Lines | Points |
|---|---|---|---|---|---|
| A: Ingest | 32.05 s | 16.6 ms | 16.9 MB | 344 | 87.6 |
| B: Index | 56.35 s | 87.3 ms | 42.1 MB | 961 | 79.6 |
| C: Join | 14.44 s | 19.3 ms | 11.3 MB | 348 | 83.1 |
| D: Traverse | 72.69 s | 118.4 ms | 65.7 MB | 424 | 73.6 |
Ideas every track shares
- Every program
mmaps/dataread-only and walks the bytes with one cursor, so no line is ever copied into a string and the page cache is never read twice. - Each one runs a single team of 12 threads. The input is cut into one chunk per thread at safe points, and the work goes in phases with short serial steps in between.
- The data gets packed small: A turns 239 MB of log into 12 MB of 4-byte records, B indexes only the terms its queries use, C measures escaped fields without ever rewriting them, and D squeezes an edge into 4 bytes.
- Answers are exact, and the output hash checks that. Percentiles are nearest rank on a counting sort, sums are integers merged in a fixed order, and D’s search is plain Dijkstra on integer weights. Nothing depends on how the threads get scheduled.
- There’s no teardown. Each process exits right after its write, and by then the threads have
handed their mappings back to the kernel in parallel, so
munmapat exit has nothing left to do.
How a chapter works
Each chapter is that track’s README.md followed by its PERF.md, pulled straight from the repo
when the book builds, so the site can’t drift from the code. The logs keep the experiments that
failed too, with their numbers, because that’s the part that’s hardest to piece together later.
Track A: Ingest
Read an access log and, for every hour and endpoint that saw traffic, print the request count, the exact 50th, 95th and 99th latency percentiles, the error count and the errors per million.
| Reference | Mine | |
|---|---|---|
| Time, full dataset, seed 1 | 32.05 s | 16.6 ms |
| Peak memory | 228 MB | 16.9 MB |
| Code lines | 56 | 344 |
| Board points | 0 | 87.6 |
That’s about 1,900 times the reference’s speed on the board’s dataset. If you only read one step in PERF.md, make it step 8, where the records started following the file’s own order.
Approach
flowchart LR
IN["access log<br/>239 MB, mapped"] --> P["parse<br/>12 threads, AVX2 line ends"]
P --> R["4-byte records<br/>endpoint id, error bit, latency"]
R --> H["hour runs<br/>counting sort per endpoint"]
H --> S["exact p50, p95, p99<br/>and error counts"]
S --> OUT["format straight into<br/>the mapped output file"]
- The log is mapped and cut into one chunk per thread at line breaks. At 239 MB it’s ten times the L3 cache, so it gets parsed exactly once; a second pass would stream it from main memory all over again.
- Each thread turns a line into a 4-byte record: endpoint id, error bit and latency. AVX2 compares find the line’s end, and the latency, the status and the end of the endpoint name are read backwards from there at fixed offsets. The latency’s digits convert in one SWAR step, and the rare latency too large for the record’s 20 bits goes on a side list. Endpoint names become small integers through one table that all threads share, so a name is compared once per occurrence and never stored per line. The whole log ends up as 12 MB of records.
- Lines arrive in long runs of the same hour, so the records stay in file order and each thread just notes where its runs of an hour start. No hour is stored per line, and nothing ever sorts the 3.1 million lines. That’s step 8, and it freed the memory that made 4-byte records and the 17 MB peak possible. The output order then falls out of one sort of the 1,842 endpoint names.
- Threads take the hours one at a time, smallest first. For one hour, a thread walks that hour’s runs in every chunk, counts lines per endpoint, places each latency with a counting sort and picks the percentiles by rank. An hour is about 43,000 lines, so its 170 KB latency buffer stays in L2 through the sort and the selection. Nearest rank on a counting sort is exact, which is why the hashes match the reference on every seed. Each hour’s records are freed as soon as they’re read, and that keeps the peak at 17 MB.
- Once every hour’s length is known, the output file gets its final size and is mapped. Each thread formats its hours straight into the file and gives those pages back. The process exits right after the write; by then the threads have returned their records and their share of the input to the kernel in parallel, and the input was unmapped before memory peaked.
Dependencies
None, just the standard library.
cd track-a && cargo +1.99.1 build --release --offline
.cargo/config.toml links statically and asks for a plain static executable instead of a static
PIE. On this track that ran the same code in 3.9% fewer user cycles, with half the iTLB misses
(PERF.md, step 40).
With another 24 hours
What’s left is mostly the parse and the page faults the kernel takes around it. perf puts the
parse at 26% of kernel samples (next_uptodate_folio, fault-around), and 47% of the formatting
phase goes to shmem page-cache insertion. First I’d fault the output pages in before the hour
pass, so the formatter never takes a fault in its inner loop. Then I’d give the parse its own
mapped copy of the input and see whether fault-around scales with more threads. After that come
the two barriers and the leader’s serial sort, which together cost 0.36 ms, 2.2% of the run.
Track A: performance log
Every step I kept cites the live-board run that measured it. Numbers marked local are from my laptop (i7-13620H, turbo off), with the old and new versions run side by side, and the changes I measured but didn’t keep are listed under the step they were tried after.
| Reference (step 0) | Final code (step 64), two board runs | |
|---|---|---|
| T | 32.05 s | 16.55 ms (run-3c87f8c35a0b), 16.87 ms (run-d83197d0cf00) |
| M | 228 MB | 16.9 MB, 17.0 MB |
| S (lines) | 56 | 344 |
| Points | 0 | 87.6, 87.3 |
| Step | Change | Run ID | T (s) | M (MB) | Points |
|---|---|---|---|---|---|
| 0 | The reference, unchanged | 32.05 | 228 | 0 | |
| 1 | Rust v1: one parse pass into 8-byte records, in-place hour sort, hour-local counting sort and selection; plus step 1b | run-8328aa9adcfa | 0.0422 | 50.9 | 72.5 |
| 2 | Output numbers written digit by digit instead of through write! | run-c283e4c2dd6a | 0.0395 | 54.4 | 72.7 |
| 3 | Workers release their share of the input before exit; hours handed out one at a time, largest first | run-74fc8ede0277 | 0.0385 | 55.2 | 72.7 |
| 4 | Endpoint names compared with one masked AVX2 compare instead of memcmp | run-9aff901d4327 | 0.0387 | 57.9 | 72.3 |
| 5 | Six numbers kept per output line; every hour formatted straight into the mapped output file | run-490479179585 | 0.0339 | 48.2 | 74.0 |
| 6 | Transparent huge pages off; formatting from a shared queue; interner lookup inlined | run-b08360e1cf8c | 0.0313 | 37.0 | 75.9 |
| 7 | 64-byte padded name copies instead of 128 | run-0793bc3ce213 | 0.0306 | 36.1 | 76.3 |
| 8 | Records in file order, 6 bytes per line, one entry per run of an hour; no hour sort | run-bbeb5bdf69ce | 0.0283 | 30.3 | 78.0 |
| 9 | Median selected first, then p95 and p99 in the shrinking upper part | run-26ed452b8751 | 0.0279 | 30.7 | 78.0 |
| 10 | 4-byte records; latencies over 19 bits on a side list | run-00fdd1e29f86 | 0.0276 | 25.0 | 79.0 |
| 11 | One team of threads summarizes and formats the hours, with a barrier between | run-23647f6bde01 | 0.0280 | 25.3 | 78.8 |
| 12 | One mmap helper for input and output; 35 fewer code lines | run-ce9384368863 | 0.0269 | 25.1 | 79.4 |
| 13 | Hour checked by comparing 8 timestamp bytes; exact 64-byte name compare without the hash; padded copies for the merge | run-b262ef9cc01a | 0.0258 | 25.2 | 79.9 |
| 14 | Lean parse on a padded mapping, SWAR number output, names merged inside the parse, sorting networks for groups of up to 64, threads spawned as a tree, and a static-pie build | run-3c59aa35895d | 0.0220 | 24.5 | 81.3 |
| 15 | 137 fewer code lines: a fixed-size name table, OnceLock hand-offs instead of a barrier leader, records written straight into each chunk | run-f13e9cd22a88 | 0.0215 | 24.4 | 82.5 |
| 16 | Records freed run by run once their hour is placed, buffers freed after the hour pass, name tables allocated once, output formatted line by line straight into place | run-1ea5237a6e04 | 0.0212 | 21.5 | 83.1 |
| 17 | The last thread to finish ends the process instead of joining the others; 15 fewer lines | run-3ba29a3569ef | 0.0209 | 21.1 | 83.5 |
| 18 | The name table’s padded copies aligned to cache lines, and its slot array a fixed-size box | run-01b9bf369035 | 0.0212 | 20.6 | 83.5 |
| 19 | The name hash takes one multiply instead of three dependent ones, and the slot is the product’s top bits | run-4d1c6d742295 | 0.0207 | 21.3 | 83.5 |
| 20 | Each output line built in a stack buffer with digit counts from the SWAR conversion; 12 fewer lines | run-1df3325795e7 | 0.0220 | 21.2 | 83.0 |
| 21 | Each small group loaded into the sorting network with one AVX2 masked load | run-c71602f005c5 | 0.0203 | 21.1 | 83.9 |
| 22 | The hour label formatted once per hour into the line buffer, and each number of up to 7 digits written with one store; 5 fewer lines | run-c71602f005c5 | 0.0203 | 21.1 | 83.9 |
| 23 | 5 fewer lines at the same speed: one use line, a recursive spawn tree, an hour as a tuple | run-6b577bd7fed9 | 0.0200 | 21.4 | 84.1 |
| 24 | 2 fewer lines with the same machine code: one use line, and no alias for the hour buffer | run-3d33fc387ebc | 0.0199 | 21.2 | 84.2 |
| 25 | 6 fewer lines with the same machine code: five variables written where they are used, and the last thread’s exit on one line | run-6223c163632a | 0.0200 | 20.9 | 84.2 |
| 26 | 3 fewer lines with the same machine code: digits a closure in its one caller, and a group’s length read where it is used | run-b3536f948213 | 0.0200 | 21.2 | 84.2 |
| 27 | The sorting network’s stages within one register take each lane’s partner from the register itself, not from the stage’s copy | run-ccf7ded5ed1d | 0.0199 | 21.0 | 84.3 |
| 28 | 3 fewer lines with the same machine code: the run pairs taken with array_windows, and two lint exceptions moved to Cargo.toml | run-ccf7ded5ed1d | 0.0199 | 21.0 | 84.3 |
| 29 | 1 fewer line with the same machine code: the network’s compare-exchange blends its minimum and maximum in one expression | run-1286db1e2359 | 0.0199 | 21.2 | 84.3 |
| 30 | The names’ output order sorted by one thread while the others start the hour pass, which needs it only at its lines | run-5d31ecdadb69 | 0.0198 | 20.9 | 84.4 |
| 31 | The hours sorted by size with each hour’s size computed once (sort_by_cached_key) | run-c441864672ce | 0.0195 | 21.1 | 84.5 |
| 32 | Hours summarized smallest first, the smallest few last, into a latency buffer of untouched zero pages | run-13fb10f4c6ee | 0.0196 | 19.1 | 84.9 |
| 33 | One endpoint table that all threads share while they parse, instead of one per thread merged after it | run-9e334b5f00fa | 0.0190 | 18.9 | 85.3 |
| 34 | The padded copies allocated uninitialized, not zeroed, and each list of large latencies reserved once | run-2c0e91287411 | 0.0190 | 18.3 | 85.4 |
| 35 | The name hash reads two 8-byte windows of the name instead of three | run-b8eed3b9c923 | 0.0187 | 18.3 | 85.6 |
| 36 | Each record stored, and each padded copy read, without a bounds check | run-921f52908023 | 0.0183 | 18.5 | 85.7 |
| 37 | 5 fewer lines with the same machine code: the hour sizes summed inside sort_by_cached_key, the name hash’s two cases as a match, and same_name folded into its one caller | run-9fe0786e93d3 | 0.0195 | 18.3 | 85.1 |
| 38 | A large latency’s record field set in the branch that lists it, instead of by a min on every line | run-e44188ffe025 | 0.0197 | 18.5 | 84.9 |
| 39 | 5 fewer lines with the same machine code: the running sum of the hour’s counts as one for_each, and a large latency listed and replaced by LARGE in one bool::then | run-89adcd077219 | 0.0196 | 18.4 | 85.1 |
| 40 | A plain static executable instead of a static PIE (relocation-model=static) | run-ebf9f6a49ad5 | 0.0190 | 17.9 | 85.5 |
| 41 | 4 fewer lines with the same machine code: the record store on one line, the counting pass without a binding for the endpoint, and each output line’s length summed in one statement | run-32182846e438 | 0.0256 | 18.0 | 82.3 |
| 42 | 1 fewer line with the same machine code: the name hash binds the length in the arms of its match | run-a6b1091911cb | 0.0192 | 18.7 | 85.4 |
| 43 | 4 fewer lines on cold paths: Interner::new instead of an impl Default, the format queue as a lazy iterator, and a new name’s padded copy from array::from_fn | run-a6b1091911cb | 0.0192 | 18.7 | 85.4 |
| 44 | 4 fewer lines in summarize: a chunk’s start found through a one-line newline closure, and the format loop as one for_each over the queue | run-a6b1091911cb | 0.0192 | 18.7 | 85.4 |
| 45 | 2 fewer lines with the same machine code: the build stage mounts its sources instead of copying them, and insert stays out of line by #[cold] alone | run-379b43c0200f | 0.0189 | 18.7 | 85.5 |
| 46 | The input prefetched five lines ahead, parse out of line with a pointer for its loop, and the endpoint interner a static | run-7eca9cefcfac | 0.0186 | 18.2 | 85.8 |
| 47 | 5.8 instructions fewer per line: the probe counts the compare mask’s trailing ones, the latency’s digits combine in three steps, and their mask is one shifted constant | run-7eca9cefcfac | 0.0186 | 18.2 | 85.8 |
| 48 | An endpoint table of 16,384 slots instead of 8,192: 1.9% of lines take a second probe instead of 3.9% | run-7eca9cefcfac | 0.0186 | 18.2 | 85.8 |
| 49 | Three rare paths of the parse marked std::hint::cold_path, so its loop keeps its count, its end and its constants in registers | run-7eca9cefcfac | 0.0186 | 18.2 | 85.8 |
| 50 | Sorting networks unrolled level by level, and a network of 128 values instead of selection for groups of 65 to 128 values | run-9a8d6161d86a | 0.0235 | 18.0 | 83.2 |
| 51 | 6 fewer lines at the same speed: the parse’s intrinsics from the file’s one wildcard import, and the interner’s padded copies zeroed in its static | run-b35557b63892 | 0.0180 | 18.8 | 85.9 |
| 52 | Endpoint names hashed with the CPU’s CRC32C instruction instead of a multiply: 9.2 M instructions fewer | run-3367489cfd2c | 0.0176 | 18.6 | 86.3 |
| 53 | 9 fewer lines in the hour pass at the same speed: the large latency taken in unwrap_or_else, empty groups filtered out, the three selections in one map, the chunk’s two releases in one | run-3367489cfd2c | 0.0176 | 18.6 | 86.3 |
| 54 | The latency’s space bounded with assert_unchecked, so reading the status and ending the name take no bounds checks: 9.8 M instructions fewer | run-c0db6c54d9a4 | 0.0225 | 18.0 | 83.8 |
| 55 | 3 fewer lines: parse an unsafe fn whose contract is the padding its assert! checked, and two range checks left to the indexes behind them | run-c0db6c54d9a4 | 0.0225 | 18.0 | 83.8 |
| 56 | 6 fewer lines at the same speed: a line’s six numbers written in one map, the format queue built without collecting the hours, the latencies placed in the whole buffer, the two counters on one line | run-c0db6c54d9a4 | 0.0225 | 18.0 | 83.8 |
| 57 | Threads started one after another by one helper instead of by a tree, so that fewer of them wait for the interner’s lock at once: 2 fewer lines | run-0899dd30b0f4 | 0.0172 | 18.4 | 86.7 |
| 58 | Each line’s id settled one line late: its name’s slot is loaded as soon as the hash is known, and the name compared with the slot’s padded copy after the next line’s front half | run-b601b34b577c | 0.0174 | 18.0 | 86.6 |
| 59 | The interner’s pages given back once the names are sorted, before the hour pass’s peak | run-b601b34b577c | 0.0174 | 18.0 | 86.6 |
| 60 | Each thread’s share of the input released right after its parse, and the whole input unmapped by one thread once all parses are done, with the interner keeping copies of the names | run-8a3bcbee7e89 | 0.0194 | 17.3 | 85.6 |
| 61 | Records with an 11-bit endpoint id and a 20-bit latency: the list of large latencies holds 1.2% of seed 1’s lines instead of 2.6% | run-6132d5943394 | 0.0164 | 17.5 | 87.3 |
| 62 | Each output line’s endpoint id and request count in one u32, so the lines that wait for the formatting take 20 bytes instead of 24 | run-6132d5943394 | 0.0164 | 17.5 | 87.3 |
| 63 | 18 fewer lines: the interner’s tables as four statics with intern and insert as plain functions, the network’s seven merge levels through a one-line macro, and a Dockerfile without WORKDIR | run-f322558253fc | 0.0165 | 17.3 | 87.5 |
| 64 | 2 fewer lines: the leader releases the interner’s three tables in one statement; the machine code is unchanged | run-4626d7369bff | 0.0167 | 17.5 | 87.3 |
Step 1: v1
Hypothesis: at 239 MB the log is ten times the L3, so the program should touch it once. Each line becomes an 8-byte record (endpoint id, hour, error bit, latency) and everything after the parse works on 25 MB of records.
- 1a, v1 alone (local only; turbo off, official harness): T 49.6 ms, M 55.3 MB, S 320. It never ran on the board on its own: the team was not registered yet when it was pushed.
- 1b, AVX2 line ends and right-to-left fields (in run-8328aa9adcfa together with 1a): the first parse scanned each endpoint 8 bytes at a time and parsed the latency digit by digit, so every line paid two loops of varying length with mispredicted exits. Now one 64-byte AVX2 compare finds the LF, the latency (up to 7 digits, 99.9% of lines) converts in one SWAR step from the word before the LF, and the status and endpoint end sit at fixed offsets before it. The endpoint hash reads three 8-byte windows instead of walking the name. Local, turbo off, under load: 59.3 → 49.6 ms wall, user CPU 380 → 321 ms.
Step 2: number formatting
The hour pass formats 127k lines with six numbers each. A phase timer showed formatting at 3.5 to 5 ms per worker, more than the selection. Writing the digits directly into a small buffer cut user CPU from 320 to 300 ms locally; on the board T went 42.2 → 39.5 ms. It cost 23 code lines (S 357 → 380), so K rose only 28.16 → 28.48.
Steps 3 to 7
- 3: the 239 MB input mapping used to be torn down by the kernel at exit, on one thread
(3.9 ms timed with an explicit
munmap). Now each worker releases its share withMADV_DONTNEEDwhen it is done. In the same run, hours go to workers one at a time from a shared counter, largest first, because night hours hold about half the lines of day hours. - 4: names vary in length, so
memcmpmispredicted its length branches on most lines. One AVX2 compare of 64 bytes against a zero-padded copy, masked to the name’s length, replaced it. - 5: the hour pass keeps six numbers per output line and the hour’s exact formatted length.
The output file then gets its final size, is mapped, and every worker formats hours straight
into place. That replaced a 3.9 ms single-threaded
write. - 6: three changes in one run. With transparent huge pages on, each thread’s 2 MB of records
straddled two 2 MB pages; turning them off with
prctl(PR_SET_THP_DISABLE)took the local peak from 50 to 36.4 MB. Formatting takes hours from a shared queue, and the interner’s lookup is forced inline (about 1 ms locally). - 7: the padded name copies shrank from 128 to 64 bytes, so more of them stay in cache: about 0.8 ms locally, and 1 MB less memory. The same code also scored T 40.2 ms in run-ce1ce7459a63; a single board run varies that much on a 31 ms program.
Step 8: records in file order
Shards upload in time order, so consecutive lines of the log almost always share an hour: seed 1’s 3.1 million lines form just 1,054 runs of one hour. Each chunk now keeps one entry per run instead of an hour field per line, so a record is the latency (4 bytes) plus the endpoint id and error bit (2 bytes), and the in-place hour sort (1.6 ms per thread) is gone. The spec promises no bound on the disorder, and correctness does not need one: a log whose hour changed on every line would have one run per line. Local, turbo off, P-cores, 40 alternating runs each: median wall 33.39 → 31.18 ms; peak memory 35.2 → 29.3 MB (three runs each).
Steps 9 to 12
- 9: each group needs three order statistics. Selecting p99 first and then p95 and p50 in the prefixes left behind visits about 2.94 n values, because those prefixes hold 99% and 95% of the group. Selecting the median first leaves p95 and p99 in the upper half, and p95 then leaves p99 in the top 5%: about 1.55 n. Local, turbo off: median 31.39 → 30.81 ms over 40 alternating runs. The first board run of this code (run-944d7fc38010) drew 32.5 ms; the table cites the second.
- 10: 97.5% of seed 1’s latencies are below 2^19 µs, about half a second. A record is now
one
u32: 12 bits of endpoint id (the spec has 1,842 endpoints), the error bit, and 19 bits of latency. A latency that does not fit goes to a per-chunk side list, and its record holds the all-ones value that sends a reader there. Local, turbo off: peak 29.5 → 23.8 MB, wall unchanged (median 31.74 → 31.39 ms over 40 runs). - 11: spawning twelve threads took up to 1 ms before the last one ran. The hour pass and the formatting now run on the same threads: between them, each waits at a barrier while one sorts the hours and maps the output file. Local, turbo off: median 30.34 → 29.91 ms (seed 1) and 30.28 → 29.83 ms (seed 2), 40 runs each.
- 12: the input and output mappings share one
mmaphelper, the imports are grouped, and a few statements that rustfmt spread over several lines are written more directly. S 525 → 490; wall time unchanged locally (median 30.04 → 29.89 ms over 30 runs).
Step 13: fewer instructions per line
perf stat on the parse showed 1.94 instructions per cycle on each of a core’s two hardware
threads, so the core retires close to four per cycle between them and every instruction left
out of the per-line work shortens the parse. Three changes, all in the parse and the merge:
- The hour was decoded from six digits on every line. A run of one hour keeps the timestamp’s
bytes 5 to 12 (
MM-DDTHH) unchanged, so each line now compares those 8 bytes with the run’s and decodes the hour only when they differ: 1,159 → 1,026 million instructions. - A probe compared the 64-bit hash stored with the name before comparing the name, a load from a 44 KB table on every line. The padded copy now holds the name’s following space too, and comparing the name plus that space is exact on its own, since endpoints never contain spaces (§2). The table grows at a quarter full instead of half: second probes went from 7.8% to 3.4% of seed 1’s lines in a simulation of the probe sequences.
- The serial merge of the chunks’ names read each name from the input, where every chunk’s copy lies in a different place: about 20,000 cache misses while all other threads waited. It now compares the chunks’ padded copies, which are then freed.
Local, turbo off, 30 alternating runs: median 30.29 → 29.60 ms (hour check) → 28.74 ms (both); instructions 1,159 → 974 million; peak memory and code lines unchanged. A second board run of the same code, run-b1fa893c8a06, measured 25.2 ms.
Step 14: fewer instructions everywhere, and a faster start
A phase split of step 13 (instrumented build, 27.7 ms locally): start-up 0.65 ms, parse 14.4 ms of wall time (13.6 per thread, plus 0.7 until the last thread starts), serial name merge 1.0, hour pass 6.3 (count 0.7, scatter 1.2, selection 3.6), formatting 3.05, releasing the input 0.65, and joining plus exit 1.0. Five changes, each measured on top of the ones before (medians of 30 interleaved runs, local, turbo off, against step 13 in the same session):
| Change | Step 14 so far | Step 13 |
|---|---|---|
| The log is mapped with 256 zero bytes after it, so each line is read as a fixed-size array with no bounds checks; bit tricks skip the method and convert the latency’s digits | 27.91 ms | 28.59 ms |
| Numbers written by a SWAR conversion and fixed 8-byte stores | 27.23 ms | 28.58 ms |
| Each thread merges its endpoint names right after its own parse, so the serial merge disappears | 26.69 ms | 28.65 ms |
| Groups of up to 64 latencies sorted by an AVX2 sorting network, which has no branches; the selection it replaces was mostly mispredicted branches. Hour pass 6.3 → 4.7 ms | 25.63 ms | 28.65 ms |
| Threads spawned as a tree, so the last of twelve starts after four spawns instead of eleven, and a static-pie build that skips the dynamic loader | 23.94 ms | 29.18 ms |
perf stat, 5 runs: instructions 989 → 817 M, cycles 530 → 446 M, branch misses 2.46 → 1.28 M.
Peak memory is unchanged (24.2 to 24.9 MB against 23.9 to 25.1 MB). S 490 → 561. The static build was
checked with an offline docker build of the track: its output for full seed 1 matches.
Tried and dropped: an LSD radix sort instead of the scatter and selection (no gain: the count pass doubled and it added page faults).
The board’s first run of this code, run-e4abec729a4f, drew 28.1 ms. The next push changed only track B, and its run of the same track A code, run-3c59aa35895d, took 21.98 ms: that is the row.
Step 15: 137 fewer lines at the same speed
S 561 → 424 (417 Rust lines and the 7-line Dockerfile), with the same output:
- The name table never grows: 8,192 slots and an assert at 4,096 names. The spec gives every seed 1,842 endpoints, so the table is never more than a quarter full.
OnceLock::get_or_initreplaces the barrier leader and its two hand-off slots, and each hour’s result goes into its ownOnceLockslot, so the hour pass collects nothing.- Records and large latencies are written straight into the chunk, and a run’s end is the next run’s start, with a sentinel after the last one.
- One queue of places instead of two, formatting appends to one
Vec, andhour_indexreads a table of days. - The name table still stores each name’s hash. Recomputing it in the merge cost 0.4 ms, because it reads the names’ bytes from the input again, cold.
Local, turbo off, against step 14 in the same sessions (ab.py, two rounds of 30 interleaved
runs): medians 24.15 and 24.26 ms against 24.52 and 24.57 ms. perf stat, 10 runs: instructions
818.8 M against 817.4 M, cycles +0.9%. memory.peak, 6 runs each: 22.4 to 23.1 MB against
22.7 to 23.8 MB. Gate: 307 pass, 0 fail.
Step 16: a lower peak
memory.current, sampled per phase, showed the peak at the end of the hour pass: all 12.4 MB of records, the hours’ lines (3 MB), every thread’s latency buffer (2.8 MB) and allocator leftovers. The records were already freed before the formatting, so they were never live together with the 10.1 MB output. Four changes:
- Each run’s records are given back (whole pages,
MADV_DONTNEED) right after their last reader, the scatter pass of their hour. - Each thread frees its latency buffer after its last hour.
- The name tables are allocated once at full size, so no grown-out buffer is left behind.
format_hourformats one line at a time into a 256-byte buffer and writes it straight into its mapped place withio::Write, so the 12 per-thread hour buffers (1.6 MB) are gone from the end. The check that each hour fills exactly its place stays.
The peak is now about even between the start of the hour pass and the end (10.1 MB of output
plus 3 MB of lines). Local, turbo off: memory.peak 22.3 to 23.1 → 19.9 to 20.4 MB (8 runs each);
ab.py medians 24.15 and 24.17 → 24.06 and 23.87 ms (two rounds of 30); instructions 818.8 →
826.6 M. S 424 → 425. Gate: 307 pass, 0 fail.
Tried and dropped: formatting whole hours during the hour pass and copying them out afterwards (0.5 MB less, but +8% T).
Step 17: the last thread ends the process
Once the output is complete, nothing is left to do but exit, so the last thread to finish calls
process::exit(0) itself instead of the main thread joining every worker. That saves about
0.35 ms of thread exits and joins. Line cuts at the same time: a timestamp outside the 72 hours
fails an expect, like the other spec guarantees, instead of returning a Result; chunk starts
come from a 4-line closure; and the mmap helper maps at least one byte, so an empty input needs
no special case.
Local, turbo off, ab.py with 50 interleaved runs in a quiet window: median 23.81 → 23.35 ms.
memory.peak 19.4 to 20.2 → 19.8 to 20.4 MB, the same within noise. S 425 → 410. Gate: 307 pass, 0
fail.
Step 18: name copies on whole cache lines
The name table keeps a 64-byte padded copy of each name for the exact compare. malloc put that
array at 16 mod 64 on every thread, so each copy straddled two cache lines and every probe
loaded both, one of them as a split load. A #[repr(align(64))] wrapper puts each copy on one
line: L1 misses 9.6 → 8.1 M. The slots became a Box<[u32; 8192]>, so the mask is a constant
and the probe has no bounds check: user instructions 829.4 → 822.3 M.
Local, turbo off, ab.py with 31 interleaved runs, two rounds: medians 23.52 → 23.09 and
23.56 → 23.07 ms, minimums 23.16 → 22.64 and 22.98 → 22.72 ms. User cycles, 4 interleaved sets
of 5 runs: 448.6 → 441.5 M. memory.peak 18.95 to 19.88 → 18.53 to 19.90 MB. S 410 → 412. Gate: 307
pass, 0 fail.
Step 19: one multiply per name hash
The name hash mixed three 8-byte windows of the name (first, middle and last) through three dependent multiply-and-rotate steps. Now the windows are rotated apart (by 0, 21 and 42 bits), XORed with the length and multiplied once by the same FxHash constant. The slot is the product’s top 13 bits, the bits every input bit reaches, which also drops the mask. In a simulation of the 8,192-slot table on seeds 1, 3 and 5, 3.2% of lines need a second probe, against 3.1% before (the old hash with top bits would need 3.8 to 7.6%). The table compares the bytes exactly, so the hash cannot change the output.
Local, turbo off: instructions 822.3 → 801.2 M; user cycles, 3 interleaved sets of 5 runs,
443.5 → 430.3 M. ab.py, 31 interleaved runs, two rounds: medians 23.25 → 22.92 and 23.40 →
22.93 ms, minimums 22.73 → 22.45 and 22.75 → 22.41 ms. memory.peak unchanged. S unchanged at
412. Gate: 307 pass, 0 fail.
Step 20: a leaner formatter, and 12 fewer lines
The board’s first run of this code, run-9ab4c13e512d, drew 26.3 ms; the next, run-1df3325795e7, 21.98 ms: that is the row.
Each output line is built in a 256-byte stack buffer instead of a Vec, the hour label is
written once per hour, and put_number writes at a cursor. The digit count comes from the
SWAR conversion itself (one tzcnt over the ‘0’ bytes) instead of a separate digits(). Phase
stamps put the format phase at 1.96 → 1.72 ms. Line cuts outside the parse and the hour pass:
the libc constants are inlined with a comment naming each flag, main reads its arguments
through one closure, and the mapping helpers lose their single-use bindings.
Local, turbo off, ab.py with 40 interleaved runs: median / min 22.84 / 22.16 → 22.70 / 22.06
ms (formatter alone 22.64 / 22.22; an earlier pair 22.91 → 22.62). perf stat -r 5: instructions
801 → 779 M, user cycles 429 → 425 M. memory.peak unchanged. S 412 → 400. Gate: 307 pass, 0
fail; a missing input still reports its path and exits 1.
Tried and dropped: faulting the output pages in ahead with MADV_POPULATE_WRITE, per hour
(slower than plain faults in a 12-thread test, 1.15 to 1.26 against 1.04 to 1.07 ms) or during the hour
pass (0.6 ms off the format phase, 1 ms onto the hour pass). A page fault on the output costs
about 1.9 µs even without contention.
Step 21: masked loads into the sorting network
A group of up to 64 latencies used to reach the sorting network one value at a time, each with
a bounds check (get().unwrap_or(MAX)), through a stack buffer. Now each register is filled by
_mm256_maskload_epi32: lanes past the group’s end read nothing and hold 0, so they sort to the
front, and the wanted ranks move up by the number of padding lanes. A real latency of 0 sorts
among them, which is still right, since every padding lane is at most every real value. The
masked lanes never fault, even past a page end.
Local, turbo off, ab.py with 31 interleaved runs, two rounds: medians 22.81 → 22.52 and
22.98 → 22.68 ms, minimums 22.24 → 22.00 and 22.24 → 21.98 ms. perf stat, 7 interleaved runs:
user cycles 423.9 → 416.8 M, branch misses 1.25 → 1.12 M, instructions 779.1 → 773.9 M.
memory.peak unchanged. S unchanged at 400. Gate: 307 pass, 0 fail.
Step 22: one store per number
Steps 21 and 22 went to the board in one push, so both rows cite run-c71602f005c5.
hour_label is folded into format_hour, which formats the label once per hour into the
line’s stack buffer. put_number writes the space and the digits of a value below 10^7 as one
8-byte store; values of 8 to 10 digits write their leading digits first, then the other seven.
Full seeds 1 to 4 have percentiles of 8, 9 and 10 digits, so the gate covers that path. Instructions
779.1 → 779.2 M: the change is lines, not time. ab.py, 40 interleaved runs, median / min:
22.74 / 21.86 ms before, 22.77 / 21.94 ms after. memory.peak unchanged. S 400 → 395. Gate: 307
pass, 0 fail.
Tried and dropped: releasing each thread’s share of the input right after its merge, to overlap the wait at the first barrier: +3.9 ms, because the TLB-shootdown interrupts hit the threads still parsing.
Step 23: 5 fewer lines
The two std::sync imports become one line; fan_out recurses instead of looping, with the
same spawn tree (12 → 6 → 3 → 1); and an hour’s result is a (lines, len) tuple with the field
docs on its type alias instead of a two-field struct. ab.py, 40 interleaved runs, median / min:
22.61 / 21.81 ms before, 22.53 / 21.58 ms after. No allocation changed. S 395 → 390. Gate: 307
pass, 0 fail.
Step 24: 2 more lines
The two remaining use std::{…} lines become one, and the three names used once (Error,
Reverse, NonZeroUsize) are written as paths where they are used; summarize_hour resizes
buffer itself instead of an alias, latencies. objdump -d of the binary is the same as step
23’s, so T and M cannot move. S 390 → 388. Gate: 307 pass, 0 fail.
Step 25: 6 more lines
release takes the page bounds straight from items.as_ptr(); parse declares its cursor i
with count and current; line_end passes its 64-byte window to equal_mask as
first_chunk(); intern computes the slot mask where it wraps; and the last thread’s exit is one
bool::then. The .text and .rodata sections are byte-identical to step 24’s, so T and M
cannot move. S 388 → 382. Gate: 307 pass, 0 fail.
Step 26: 3 more lines
digits moves into summarize_hour, its only caller, as a one-line closure, and percentiles
reads group.len() where it used n. .rodata is byte-identical to step 25’s; .text differs
in four compares of the group length, cmp $9; jae becoming cmp $8; ja and so on, the same test
in an instruction of the same size, so T and M cannot move. S 382 → 379. Gate: 307 pass, 0 fail.
Step 27: the network’s in-register stages without the copy
Each stage of sort_network compares every lane with a partner, and a stage reads the partners
from old, a copy of the registers taken before the stage, because a stage that pairs two
registers overwrites the first before the second reads it. A stage within one register (m < 8)
pairs lanes of the same register, which has not been written yet when its partners are read, so
it now permutes the register itself, and the compiler no longer stores and reloads it.
Instructions 774.28 → 770.72 M (-0.46%). Cycles of the network per call, rdtsc on an instrumented
copy, two runs: up to 16 latencies 125 → 117, up to 32 623 → 563, up to 64 1,414 → 1,230. The
percentiles and lines of an hour, timed per hour, 5 runs each: median 2.34 → 2.29 ms per thread.
That is about 0.06 to 0.1 ms per thread, under 0.5% of the run: user cycles 417.21 → 416.96 M over
15 interleaved runs and ab.py (61 runs per round, two rounds: medians 22.37 → 22.36 and
22.43 → 22.55 ms) are within noise. S unchanged at 379. Gate: 307 pass, 0 fail.
Step 28: 3 more lines
The plan loop destructures each pair of runs from array_windows() instead of indexing a
windows(2) slice, and the two lints the code breaks on purpose, inline_always for intern
and wildcard_imports for the AVX2 intrinsics, are allowed in Cargo.toml with their reasons
instead of #[expect] on the items. .text and .rodata are byte-identical to step 27’s, so T
and M cannot move. S 379 → 376. Gate: 307 pass, 0 fail.
Steps 27 and 28 went to the board in one push, so both rows cite the same run.
Step 29: 1 more line
With the partner named p (step 27), the minimum and maximum fit inside the blendv call, so
the (low, high) binding goes. .text and .rodata are byte-identical to step 28’s. S 376 → 375.
Gate: 307 pass, 0 fail.
The first board run of this code, run-9d734179de5e, drew 21.8 ms with the same machine code as step 28; the row cites the next run of the same commit’s code.
Step 30: the name sort off the critical path
Timed with rdtsc inside the plan, the barrier leader took about 0.28 ms while 11 threads waited,
0.16 to 0.21 ms of it sorting the names into output order. No hour needs that order before its
lines, and a thread’s first hour spends about 0.4 ms counting and scattering before them. So the
leader now publishes the runs and hour sizes first (plan.set), then sorts and publishes the
order in a second OnceLock, and summarize_hour waits on it only when it reaches its lines.
ab.py against step 29, interleaved: 101 runs twice, medians 22.58 → 22.37 and 22.46 → 22.26 ms,
minimums 21.59 → 21.49 and 21.93 → 21.63 ms; 60 runs on seed 1, 22.45 → 22.33 ms, and on seed 2,
22.56 → 22.23 ms. memory.peak medians 20.12 → 20.09 MB (5 runs each). S 375 → 377. Gate: 307
pass, 0 fail.
Not kept: giving out the last 10% of each thread’s share as 48 pieces from a shared counter, so threads that start late do less. It evened the parse’s end spread from 1.08 to 0.36 ms but cost 1.5% (median 22.44 → 22.77 ms, user cycles +1.5%): a thread that finishes early already speeds up its hyperthread sibling, and the extra merges queue on the interner’s lock.
Step 31: each hour’s size computed once
The leader orders the hours by size for the hour pass, and sort_by_key summed an hour’s run
lengths in every comparison, about 800 times for 72 hours. sort_by_cached_key sums each once.
The leader’s plan before plan.set, timed with rdtsc over 31 interleaved runs: median 0.129 →
0.099 ms, minimum 0.105 → 0.083 ms. That is 0.13% of the run, below what ab.py resolves
(two rounds of 101: medians 22.34 → 22.37 and 22.22 → 22.30 ms). S unchanged at 377. Gate: 307
pass, 0 fail.
Step 32: a lower peak from the order of the hours
Every thread of an instrumented copy read memory.current at each step of its work (local, turbo
off, seed 1, three runs). The peak was not at the end, where the output fills up, but at the
start of the hour pass. Each worker’s first hour was one of the twelve largest, about 70,000
lines, and resize wrote zeros over its 280 KB latency buffer before the first latency, while
an hour’s records go back to the kernel only after their scatter. Within 0.6 ms of the start,
memory.current rose by 2.6 to 3.1 MiB to 19.4 to 20.5 MiB. The parse had topped out at 17.8 to 18.4 MiB
and the finished output at 19.3 to 19.5 MiB.
Two changes:
- Each worker’s latency buffer is allocated once, with room for every line of the log
(
vec![0; len / MIN_LINE + 1], 24 MB of address space). glibc’s malloc maps a request that large as fresh zero pages, whichcallocleaves untouched, so a page takes memory only once a latency lands in it. - The hours go smallest first, so each buffer grows a little at a time while earlier hours free
their records. The
threadssmallest hours go last instead, so every worker ends on a short hour, as with largest first.
In four runs of the same probe, the hour pass now tops out 0.2 to 1.2 MiB above where it starts, at
17.5 to 18.0 MiB, and the output at 16.8 to 17.2 MiB. The peak is the end of the parse, 17.6 to 18.3 MiB,
where the threads still parsing hold their name tables (about 190 KB each) on top of the
records. Local, turbo off: memory.peak, 20 alternating runs each, median 19.89 → 18.15 MiB on
seed 1; 10 each on seed 2, 19.97 → 17.96 MiB. ab.py, 61 interleaved runs, two rounds on seed
1: medians 22.56 → 22.33 and 22.72 → 22.53 ms, minimums 21.49 → 21.53 and 21.80 → 21.89 ms; one
round on seed 2: median 21.49 → 21.25 ms, minimum 20.98 → 20.89 ms. S 377 → 378. Gate: 310 pass,
0 fail (full seeds 1 to 7 and 10 to 12, 300 tiny seeds).
Tried and dropped, medians of memory.peak over 8 to 12 alternating runs, local, turbo off:
- The untouched buffer alone, largest first: 19.84 to 19.90 MiB. Most endpoints have a few latencies an hour, and their places are spread over the whole buffer, so its pages fill early anyway.
- Smallest first all the way: 17.91 to 18.04 MiB, but the longest hours then start last and the
threads finish apart:
ab.pymedians +0.9% and +1.9% (60 runs, two rounds). - The 12 or the 24 smallest hours first, then largest first: 19.56 and 19.03 MiB.
- The kept order with the buffer grown by
resize: 18.72 MiB. malloc_trim(0)after each thread’s merge, to give its freed name table back: 17.72 against 18.04 MiB in one session, 18.01 against 17.99 MiB in another.
Step 33: one endpoint table for all threads
Each thread used to give endpoint names ids in a table of its own, about 190 KB once written
(slots, names and padded copies), then merge it into a shared table under a lock, and the hour
pass mapped every record’s chunk id to a shared id through one more table per chunk. Now all
threads give out ids in one table while they parse (Interner). A lookup takes no lock: it
loads a slot with Acquire, and a thread that adds a name writes the name and its padded copy
before it stores the id with Release. Adding takes a mutex. Under it, the thread checks that
the empty slot it found is still empty; if another thread filled it in the meantime, it probes
again. The records hold shared ids, so the merge and the id table go.
The same probe as in step 32 (four runs, local, turbo off, seed 1): the end of the parse falls from 17.6 to 18.3 to 16.2 to 16.4 MiB. The hour pass is now the peak, at 17.9 to 18.2 MiB: the per-thread tables had left freed memory in the threads’ malloc arenas, which the hour pass’s small allocations reused, and now those come from new pages. The output ends at 16.6 to 17.0 MiB.
Local, turbo off: memory.peak, 20 alternating runs, median 18.14 → 17.65 MiB on seed 1; 10 each
on seed 2, 17.91 → 17.81 MiB. ab.py, 61 interleaved runs, two rounds on seed 1: medians
22.28 → 21.54 and 22.20 → 21.42 ms, minimums 21.44 → 20.94 and 21.35 → 20.83 ms; one round on
seed 2: median 21.77 → 21.13 ms, minimum 21.30 → 20.49 ms. perf stat (10 runs, twice):
773.7 → 747.8 million user instructions, task clock 220.1 → 212.7 ms. The hour pass no longer
loads and bounds-checks an id for each record, twice, and the merge and the per-thread inserts
are gone. S 378 → 381. Gate: 310 pass, 0 fail (full seeds 1 to 7 and 10 to 12, 300 tiny seeds).
Seeds 1 to 3, 15 runs each on 12, 4 and 2 CPUs: all 135 outputs match the reference hash.
Step 34: two buffers the allocator had filled
A copy of /proc/self/smaps at the barrier after the parse (local, seed 1, two runs) counted
13,312 to 13,324 KiB of anonymous memory, 12,144 KiB of it records. Two parts of the rest needed
no memory:
- The padded copies.
Box::new_zeroed_slicegets a block aligned to 64 bytes fromposix_memalignand then writes zeros over it, so all 256 KiB of the table were in memory, though the 1,842 copies fill 115 KiB. The table now holdsMaybeUninitentries and comes fromBox::new_uninit_slice, whose pages take memory only as copies are written: 260 → 116 KiB. - The lists of large latencies. Each grew by doubling inside its thread’s malloc arena, and every buffer it outgrew stayed there. Reserved like the records, with room for a large latency on every line, a list is a mapping of its own whose untouched pages cost nothing. The thread arenas went from 424 to 436 to 96 KiB, the main heap from 308 to 312 to 148 KiB.
At the barrier: 13,312 to 13,324 → 13,020 KiB. Local, turbo off: memory.peak, 20 alternating runs,
median 17.66 → 17.36 MiB on seed 1; 10 each on seed 2, 17.58 → 17.38 MiB. ab.py, 61
interleaved runs, two rounds on seed 1: medians 21.46 → 21.43 and 21.48 → 21.52 ms, minimums
21.01 → 21.02 and 21.02 → 21.05 ms. S 381 → 382. Gate: 310 pass, 0 fail (full seeds 1 to 7 and
10 to 12, 300 tiny seeds).
The peak is still the start of the hour pass. In the same probe as step 33, anonymous memory rises by 1.1 MiB within 0.2 ms of it, as every worker writes its first latency buffer while the records are all still there, and memory.current tops out 1.4 to 1.8 MiB above the end of the parse. Tried and dropped, medians of memory.peak over 20 alternating runs, local, turbo off:
- Hours smallest first all the way, without moving the smallest to the end: 0.26 to 0.32 MiB
lower, but
ab.pymedian 21.50 → 21.72 ms (+1.0%, 61 runs). - The 12 smallest hours first and the next 12 last: 0.14 MiB higher than the kept order.
- Each hour’s lines released once formatted (1 line): in the probe the end of the output falls from 16.6 to 17.0 MiB (step 33) to 14.3 to 14.7 MiB, but the hour pass still sets the peak (17.47 against 17.42 MiB without it).
Step 35: two windows per name hash
A phase split of step 34 (instrumented build, 30 runs, local, turbo off; ms from before the
fork): main starts at 0.57, the first worker at 0.80 and the last at 1.33. The parse takes
11.1 to 11.7 ms per thread and ends between 12.39 and 12.64, the plan 0.07. The hour pass ends at
17.12 to 17.55: per thread, counting 0.60 ms, the scatter 1.10, releasing records 0.24, and
percentiles and lines 2.41. Formatting takes 1.67 ms per thread, releasing the input 0.59, the
last thread calls exit at 20.40, and the parent’s wait returns 0.79 ms later.
perf stat counts 238.5 user instructions per line at 1.99 per cycle on each hyperthread, with
0.05 L2 misses per line and 1.4% of cycles stalled on an L1 miss: the parse is bound by
instructions, not by memory. The name hash read three 8-byte windows of the name, and the middle
one cost a subtraction, a shift, a bounds check, a load, a rotate and an XOR on every line. Now
it reads the first and the last only. In a simulation of the 8,192-slot table, 3.6 to 4.7% of lines
need a second probe instead of 3.1 to 3.4% (seeds 1, 3 and 5), each a mispredicted branch: far less
than the instructions saved.
Local, turbo off: instructions 739.4 → 714.2 M, branch misses 1.09 → 1.08 M. ab.py, 61
interleaved runs, four rounds: medians 21.58 → 21.12, 21.53 → 21.14, 21.58 → 21.11 and
21.56 → 21.22 ms, minimums 21.10 → 20.62, 20.93 → 20.55, 20.98 → 20.39 and 21.17 → 20.74 ms.
memory.peak, 12 alternating runs: median 18.17 → 18.14 MB. S unchanged at 382. Gate: 310 pass,
0 fail.
Step 36: two bounds checks fewer per line
Every line paid for two bounds checks that could never fail, whatever the input. The store of
its record: line_end starts looking at byte MIN_LINE - 1, so each line, malformed or not,
moves on by at least MIN_LINE bytes, and the chunk’s len / MIN_LINE + 1 records always have
room. And the padded copy read for every probe: an id in a slot is below the count of names,
which insert keeps within the 4,096 copies. Both are now unchecked, with that argument as the
SAFETY note. The other checks on the line stay: the name and status offsets come from the
line’s bytes, and only well-formed input keeps them in range.
The compiler’s register allocation decided the gain. Shifting the error bit where it is computed, rather than in the record’s expression, gave the same instruction count, but the loop then reloaded a pointer from the global offset table on every line instead of keeping it in a register, and gained about 0.05 ms instead of 0.25.
Local, turbo off: instructions 714.2 → 701.5 M (4 per line), cycles 375.6 → 371.7 M (5 runs).
ab.py, 61 interleaved runs, four rounds: medians 21.16 → 20.89, 21.14 → 20.91, 21.17 → 20.90
and 21.13 → 20.93 ms, minimums 20.67 → 20.30, 20.60 → 20.18, 20.61 → 20.51 and 20.80 → 20.50 ms.
memory.peak, 11 alternating rounds on each of seeds 1 to 7 and 10 to 12: median 18.09 → 18.07 MB.
S 382 → 385. Gate: 310 pass, 0 fail.
Step 37: 5 fewer lines
The plan hands the closure that sums an hour’s run lengths straight to sort_by_cached_key
instead of binding it first. hash picks between the masked short name and the last window
with a match on the length, whose two arms rustfmt keeps on two lines where the if/else
took four. same_name, a one-line function with one caller, is folded into Interner::intern,
whose doc now carries its explanation. .text and .rodata are byte-identical to step 36’s, so
T and M cannot move. S 385 → 380. Gate: 310 pass, 0 fail. The board’s run of this code, run-9fe0786e93d3,
drew 19.5 ms, against 18.3 ms for step 36’s identical machine code: a slow draw.
Step 38: no min on every line
The record’s latency field was micros.min(LARGE), a compare and a conditional move on
every line, though the branch just before it, which lists a large latency, has already decided
the same thing. That branch now sets the field to LARGE itself, and other lines store the
latency as it is.
Local, turbo off: instructions 701.5 → 692.3 M (3 per line). ab.py, 61 interleaved runs, six
rounds: medians 20.98 → 20.91, 21.04 → 20.91, 20.98 → 20.85, 20.99 → 20.77, 20.97 → 20.85 and
20.98 → 20.88 ms, minimums 20.37 → 20.28, 20.24 → 20.02, 20.50 → 20.39, 20.46 → 20.03,
20.22 → 20.16 and 20.56 → 20.28 ms. memory.peak, 11 alternating rounds on each of seeds 1 to 7 and
10 to 12: median 18.08 → 18.13 MB, with no change to any allocation. S 380 → 381. Gate: 310 pass,
0 fail.
The board measured this code in the run of commit 3e78ba2, which changed only track C:
run-e44188ffe025 drew 19.7 ms, against 18.3 ms for step 36’s code, a slow draw.
Step 39: 5 fewer lines
The running sum that turns summarize_hour’s counts into ends is one for_each over the range
instead of a three-line for loop. parse lists a large latency and leaves LARGE in its place
with one bool::then, whose mem::replace hands the old value to the side list, instead of a
four-line if. .text and .rodata are byte-identical to step 38’s, so T and M cannot move.
S 381 → 376. Gate: 310 pass, 0 fail.
The board’s run, run-89adcd077219, drew 19.6 ms: the fourth draw of 19.5 to 19.7 ms in a row since
step 36’s 18.3 ms, on code that has changed by 3 instructions per line since.
A second run of the same code, run-a0af33fbe24c (commit f25c5c2, which changed only track C),
measured 19.7 ms, 18.1 MB and 85.1 points.
Step 40: a plain static executable
The binary was a static PIE: the kernel loads it at a random address and it relocates itself
before main. Built with -C relocation-model=static, it is a plain static executable at a
fixed address instead, with the same code apart from addressing: 692.3 → 689.4 M instructions.
Yet it ran 3.9% fewer user cycles (383.7 → 368.8 and 382.7 → 368.5 M, 10 runs each), with
about as many dTLB load misses (81,200 → 77,700) and half the iTLB misses (15,300 → 7,500).
Kernel cycles and page faults did not move. The phase split puts all of it in the parse: 10.64
→ 10.03 and 10.55 → 10.06 ms per thread (two sets of 30 runs), while start-up, the hour pass
and formatting kept their lengths. It is not the alignment of the code: aligning every function
of the PIE build to 64 bytes (-align-all-functions=6) changed nothing.
Local, turbo off: ab.py, 61 interleaved runs against step 38’s code, four rounds: medians
20.47 → 19.97, 20.48 → 19.93, 20.62 → 20.13 and 20.90 → 20.36 ms, minimums 20.17 → 19.61,
19.96 → 19.65, 20.15 → 19.50 and 20.27 → 19.59 ms; against step 39’s build, two clean rounds:
20.59 → 20.09 and 20.80 → 20.48 ms. memory.peak, 11 alternating rounds on each of seeds 1 to 7 and
10 to 12: median 18.18 → 18.21 MB. S unchanged at 376. Gate: 310 pass, 0 fail.
Step 41: 4 fewer lines
With no min in it since step 38, parse’s record store fits on one line as an unsafe block
around the assignment. summarize_hour’s counting pass indexes both counters with the record’s
endpoint directly instead of binding it first. Its width closure counts the space before a
number with the number’s digits, so an output line’s length is one statement, which sums the
numbers first: summed after the name’s length, the same arithmetic compiled to different code.
.text is byte-identical to step 40’s, and .rodata differs only in the line numbers of 30
panic locations, which the plain static executable of step 40 keeps there, so T and M cannot
move. S 376 → 372. Gate: 310 pass, 0 fail.
The board’s run, run-32182846e438, drew 25.6 ms against 19.0 ms for step 40’s identical .text.
In the same push, track D’s unchanged code drew 132.6 ms against its usual 122 to 128 ms: the box
was slow for that run.
Step 42: 1 fewer line
hash binds the name’s length in the arms of its match instead of in a let before it.
.text is byte-identical to step 41’s, and .rodata differs only in the line numbers of panic
locations, so T and M cannot move. S 372 → 371. Gate: 310 pass, 0 fail.
Step 43: 4 fewer lines on cold paths
- The interner’s constructor is
Interner::new, first in itsimpl, instead of animpl Defaultof its own, which onlysummarizecalled. - The format queue is the iterator itself, in its mutex: each
nextcuts the hour’s place from the rest of the output as it hands the hour out, so no vector of places is collected first. The hours now go out first to last;pophanded them out last to first. insertbuilds a new name’s padded copy witharray::from_fn, which keeps byteiof the window fori <= n, instead of copying the window and zeroing its tail withfill.
The machine code changes in Interner::insert, which runs 1,842 times a seed, and in the work
closure from the format queue on; elsewhere only addresses of constants and stack slots moved.
ab.py against step 41, two rounds of 60 runs: medians 20.15 → 20.10 and 19.99 → 19.85 ms,
minimums 19.50 → 19.34 and 19.44 → 19.24 ms. memory.peak, 24 alternating runs on seed 1: median
18.29 → 18.13 MB. S 371 → 367. Gate: 310 pass, 0 fail.
Step 44: 4 fewer lines in summarize
start finds a chunk’s first line through a one-line newline closure, the position of the LF
before the chunk’s nominal start, instead of a block with a binding of its own. The threads take
hours from the queue in one iter::from_fn(...).for_each(...) instead of a while let over a
named closure; the lock is still taken and released inside the closure, so no thread holds it
while it formats. The machine code changes only around those lines of the work closure and in
its stack slots before the hour pass. ab.py, 40 interleaved runs, two rounds: medians
20.20 → 20.07 and 20.16 → 20.12 ms against step 43 (step 41’s code: 20.25 and 20.25 ms in the
same rounds). memory.peak, 24 alternating runs on seed 1: median 18.13 MB for both; on seeds 3, 7
and 11, 8 runs each, within 0.02 MB of step 41. S 367 → 363. Gate: 310 pass, 0 fail.
The board measured steps 42 to 44 together, pushed as one, in run-a6b1091911cb: 19.2 ms.
Step 45: 2 fewer lines
The Dockerfile’s build stage mounts its context (RUN --mount=type=bind,target=/src) instead of
copying it with COPY . ., and cargo builds into --target-dir /out, since the mount is
read-only. harness/dockerfile_check.py accepts a bind mount of the context, and every builder
that builds us is BuildKit: Depot, the board’s rootless BuildKit fallback and final scoring’s
docker build. A local docker build --network=none of the old and the new Dockerfile gave
byte-identical binaries. insert drops #[inline(never)]: #[cold] alone keeps it out of
line. .text is byte-identical to step 44’s, and .rodata differs only in the line numbers of
27 panic locations, so T and M cannot move. S 363 → 361. Gate: 310 pass, 0 fail.
Step 46: the input prefetched, and parse on its own
parse was inlined into the work closure, and its speed depended on where its loop landed. A
change elsewhere in that function, or one that only moved the loop, raised the L1 misses by half,
all on the input: L1-dcache-load-misses:u on seed 1 was 4.27 M for step 45, and 6.72 to 6.74 M both
with parse out of line and with a change to hour_index alone, whose cycles:u rose 3.7 to 4.1%
though they ran about 6.4 M fewer instructions (battery, perf stat, 40 interleaved runs, two
rounds). Step 45’s layout was the lucky one: the hardware prefetcher kept the input in L1 for it
and not for the others. Five changes:
- Each line prefetches the two cache lines from 384 bytes on (
_mm_prefetchwith_MM_HINT_T0), about five lines ahead. With them the misses are 3.85 M in every layout tried: 3.85 to 3.86 M in a copy whoseparsean#[inline(never)]onsummarize_hourmoved 0x1b0 bytes on, and its cycles:u matched too (346.6 and 346.1 M against 346.6 and 347.1 M). parseis#[inline(never)]. The work closure realigns its stack to 32 bytes and so keepsrbpas its frame pointer; out of line, the loop hasrbpfor itself.- The loop moves a pointer to the line instead of an index into the log: 9.7 M instructions fewer.
- The status bit and a large latency are taken before the lookup, so fewer values live through it.
- The interner is a static,
ENDPOINTS, so its tables lie at fixed addresses: a probe loads no pointer to them, andparsekeeps no register for them: 9.6 M instructions fewer. AOnceLockstarts out nonzero, so the tables take 393 KB of.data; only the pages that are touched are read in, as with the heap pages they took before. The static alone gained nothing on step 45’s code (see the experiments below): inlined into the work closure, the loop had no register to give back.
parse now has its own symbol, 0x8f1 bytes; the work closure shrank from 0x40ba to 0x36de bytes.
On AC power (local, P-cores, turbo off), ab.py, 61 interleaved runs, four rounds, against step
45: medians 20.33 → 19.73, 20.23 → 19.70, 20.21 → 19.70 and 20.25 → 19.74 ms (-2.5 to -3.0%),
minimums 19.67 → 19.12, 19.43 → 19.07, 19.63 → 19.18 and 19.50 → 19.04 ms. Timed by fork, exec and
wait, as the board’s timer does, 41 runs, two rounds: medians 19.07 → 18.50 and 19.09 → 18.47 ms.
Without the static, the other four changes measured 19.81, 19.83, 19.83 and 19.78 ms in the same
rounds, and 18.66 and 18.66 ms by the second timer. Counters, measured on battery power, so only
the counts compare (perf stat, 40 interleaved runs, two rounds): instructions:u 690.9 → 662.6 M
(-4.1%), cycles:u medians 362.8 → 346.6 M and 363.0 → 347.1 M (-4.4%), minimums 351.2 → 326.9 M and
347.7 → 328.3 M, L1-dcache-load-misses:u 4.27 → 3.85 M. memory.peak, five alternating rounds on
seeds 1, 2, 3, 5, 7, 10 and 11: median 18.09 → 18.09 MB. S 361 → 367. Gate: 310 pass, 0 fail; full
seeds 1 to 7 and 10 to 12 give the reference hashes; clippy reports no warnings.
Step 47: 5.8 instructions fewer per line
Three cuts in the probe and the latency, each measured alone (instructions:u, seed 1):
- The probe counts the compare mask’s ones. A probe matches when the first
n + 1bytes agree, the name and the space: when the mask starts with more thannones.trailing_ones() > nran 5.5 M instructions fewer, 1.8 per line, than masking off the bits abovenand testing the rest. - The digits in three steps.
eight_digitscombines the digit lanes into pairs, the pairs into fours and the fours into the number, each with one multiply byk·2^s + 1, a shift and a mask, for k = 10, 100 and 10,000. Step 45’s form, which took the pairs into the number with two multiplies side by side, ran 9.2 M instructions more, 3 per line. - The digit mask as one shifted constant,
0x0F0F_0F0F_0F0F_0F0F << s, instead of the constant and a shifted all-ones mask: 2.9 M instructions fewer.
On AC power (local, P-cores, turbo off), ab.py, 61 interleaved runs, four rounds, against step
46: medians 19.73 → 19.54, 19.70 → 19.61, 19.70 → 19.63 and 19.74 → 19.54 ms (-0.4 to -1.0%),
minimums 19.12 → 18.92, 19.07 → 19.06, 19.18 → 19.08 and 19.04 → 18.91 ms; timed as the board does,
41 runs, two rounds, medians 18.50 → 18.46 and 18.47 → 18.47 ms. Counters, measured on battery
power, so only the counts compare (perf stat, 40 interleaved runs, two rounds): instructions:u
662.6 → 644.6 M (-2.7%), cycles:u medians 346.6 → 343.4 M and 347.1 → 342.9 M (-0.9 to -1.2%),
minimums 326.9 → 330.6 M and 328.3 → 313.7 M, L1-dcache-load-misses:u 3.85 → 3.85 M. A copy whose
parse an #[inline(never)] on summarize_hour moved 0x1b0 bytes on ran the same: cycles:u 344.5
and 342.2 M against 345.8 and 343.1 M in another session, L1 misses 3.85 M. memory.peak, as in step
46: median 18.09 → 18.00 MB. S 367 → 366. Gate: 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the
reference hashes; clippy reports no warnings.
Step 48: an endpoint table of 16,384 slots
With 8,192 slots, 3.9% of seed 1’s lines took a second probe, and each one is a mispredicted
branch. A simulation of the table, names inserted in file order, gives 1.9% with 16,384 slots:
4.20% → 2.27% on average over seeds 1 to 7 and 10 to 12, and at most 3.33% (seed 11). branch-misses:u
went 1.09 → 1.01 M a run (perf stat, 10 interleaved runs). The slots take 32 KB more of .data,
64 KB in all, and the L1 misses rose 3.85 → 3.93 M.
ab.py cannot tell this step from step 47. On AC power (local, P-cores, turbo off), 61 interleaved
runs, four rounds: medians 19.54 → 19.54, 19.61 → 19.60, 19.63 → 19.65 and 19.54 → 19.49 ms,
minimums 18.92 → 19.03, 19.06 → 18.90, 19.08 → 18.93 and 18.91 → 18.67 ms; timed as the board does,
41 runs, two rounds, medians 18.46 → 18.49 and 18.47 → 18.36 ms. Without the static interner of
step 46, the same change measured 19.72 → 19.53, 19.76 → 19.62, 19.75 → 19.52 and 19.65 → 19.58 ms
in the same rounds. Counters, measured on battery power, so only the counts compare (perf stat,
40 interleaved runs, two rounds): instructions:u 644.6 → 643.2 M (-0.2%), cycles:u medians
343.4 → 340.9 M and 342.9 → 341.7 M (-0.4 to -0.7%), and 345.8 → 342.1 M and 343.1 → 340.7 M in a
second session, minimums 330.6 → 327.2 M and 313.7 → 321.9 M. A copy moved as in step 47 ran the
same: cycles:u 342.1 and 340.3 M against 342.1 and 340.7 M, L1 misses 3.94 M. memory.peak: median
18.00 → 18.12 MB, and 18.40 → 18.26 MB in an earlier session. S 366 → 366. Gate: 310 pass, 0 fail;
full seeds 1 to 7 and 10 to 12 give the reference hashes; clippy reports no warnings.
Step 49: three rare paths marked cold
std::hint::cold_path() marks a new run, a latency of 8 digits or more and a second probe. Without
the hints, LLVM’s guess at how often each runs kept the loop’s record count and its end on the
stack and rebuilt the LF pattern and two 64-bit constants on every line; with them, those stay in
registers, and the hot path has two taken branches fewer per line (br_inst_retired.near_taken:u
40.9 → 34.7 M): 26.0 M instructions fewer, 8.4 per line. Each hint alone, on an earlier form of
step 48: the second probe -16.7 M, the long latency -3.4 M, the new run -0.1 M; the three together
-26.0 M. Hints on a large latency, on a line of more than 103 bytes and on a name of 64 bytes or
more gained nothing.
On AC power (local, P-cores, turbo off), ab.py, 61 interleaved runs, four rounds, against step
48: medians 19.54 → 19.36, 19.60 → 19.41, 19.65 → 19.37 and 19.49 → 19.33 ms (-0.8 to -1.4%),
minimums 19.03 → 18.49, 18.90 → 18.82, 18.93 → 18.62 and 18.67 → 18.81 ms; timed as the board does,
41 runs, two rounds, medians 18.49 → 18.25 and 18.36 → 18.14 ms. A copy whose parse an
#[inline(never)] on summarize_hour moved 0x170 bytes on timed the same: medians 19.35, 19.40,
19.40 and 19.36 ms, and 18.16 and 18.31 ms. Counters, measured on battery power, so only the counts
compare (perf stat, 40 interleaved runs, two rounds): instructions:u 643.2 → 617.2 M (-4.0%),
cycles:u medians 340.9 → 334.1 M and 341.7 → 333.3 M (-2.0 to -2.5%), minimums 327.2 → 321.1 M and
321.9 → 318.0 M, L1-dcache-load-misses:u 3.93 → 3.94 M; the moved copy 333.8 and 333.6 M.
memory.peak: median 18.12 → 18.17 MB. S 366 → 369. Gate: 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12
give the reference hashes; clippy reports no warnings.
Steps 46 to 49 together, in the same rounds: medians 20.33 → 19.36, 20.23 → 19.41, 20.21 → 19.37 and 20.25 → 19.33 ms (-4.1 to -4.8%), and 19.07 → 18.25 and 19.09 → 18.14 ms timed as the board does. Without the static interner the four steps end level with these, at 19.40, 19.40, 19.44 and 19.27 ms and at 18.17 and 18.19 ms, with 8.4 M instructions more; the static measured ahead at steps 46 and 47, so it stayed.
Steps 46 to 49 reached the board in one push. Its run, run-7eca9cefcfac, measured 18.6 ms and 18.2 MB, against 18.8 and 19.1 ms for step 45’s code in its last two runs (run-6e4daa8e2dbc, run-8a8f22b6a3dc).
Step 50: sorting networks unrolled level by level
The network’s two loops become one call per merge level, merge::<R, L>, each a loop of constant
trip count L around a stage function. LLVM unrolls those loops before it inlines the stages, so
every stage sees a constant partner distance: its masks are constants, each register’s partner is a
fixed register, and the networks of 32, 64 and 128 values come out without loops, blends on runtime
masks or copies to the stack. A network of 128 values (R = 16) then beats selection too, and takes
the groups of 65 to 128 values, 2.4% of them. In a microbenchmark over seed 1’s 126,908 groups (one
thread, ns per group), 17 to 32 values went 99.5 → 52.7, 33 to 64 values 253 → 100, and 65 to 128 values 687
(selection) → 389 to 432; all groups 15.05 → 12.87 ms. As a loop, the 128-value network took 923 ns,
more than selection.
On step 45 the same change lost 2% (ab.py, 61 interleaved runs, medians 20.15 → 20.57 and
20.17 → 20.53 ms) although it ran 17 M instructions fewer: the parse was then inlined in the work
closure, and the larger closure gave it other registers and stack slots. With the parse out of line
in both builds, the networks took 2.5 to 2.9% fewer cycles:u. Since step 46 the parse is a function of
its own, and here its instructions are step 49’s; only the address of the endpoint table in them
changes.
ab.py, 61 interleaved runs, four rounds, against step 49: medians 19.39 → 19.09, 19.34 → 19.08,
19.36 → 19.14 and 19.34 → 19.03 ms (-1.1 to -1.6%), minimums 18.71 → 18.32, 18.74 → 18.36,
18.93 → 18.52 and 18.76 → 18.43 ms; the first two rounds ran a build that also had #[inline] on
merge and stage, with a byte-identical .text. perf stat, 10 interleaved rounds of 3 runs:
instructions:u 616.0 → 598.9 M (-2.8%), cycles:u median 337.8 → 332.7 M (-1.5%). memory.peak, five
alternating rounds on seeds 1, 2, 3, 5, 7, 10 and 11: median 18.34 → 18.24 MB. S 369 → 379. Gate:
310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; clippy reports no warnings.
The board’s run, run-9a8d6161d86a, drew 23.5 ms, a slow draw: in the same run, track C’s unchanged code drew 60.1 ms, against its usual 27 ms, and track D’s 135.9 ms, against 122 to 127 ms. A second run of the same commit, run-65986567a603, drew 17.9 ms, and a third, run-148a82d5f70d, 17.6 ms.
Step 51: 6 fewer lines
parse and equal_mask lose their own use std::arch lines: the wildcard import that step 50 put
at the top of the file brings in the same intrinsics, and equal_mask names them in full, with its
two halves in one map. The interner’s padded copies are UnsafeCell<Padded> instead of
UnsafeCell<MaybeUninit<Padded>> and start out as zeros, written in the static’s initializer, so
Interner::new goes, and with it the two assume_init_ref calls and the unsafe block that made
the uninitialized array. The static is in .data anyway, since a OnceLock starts out nonzero, and
.data keeps its size. .text and .data are byte-identical to step 50’s, and .rodata differs
only in the line numbers of panic locations, so T and M cannot move: ab.py, seven interleaved
rounds (three of 41 runs, four of 61), medians 19.25 → 19.12, 19.16 → 19.11, 19.03 → 18.96,
19.06 → 19.03, 18.99 → 19.05, 19.06 → 19.03 and 19.69 → 19.62 ms. S 379 → 373. Gate: 310 pass,
0 fail.
The board drew 18.0 ms at 18.8 MB for it in run-b35557b63892, 19.5 ms for the same code in run-dbba1dbc4ea4, and 17.7 ms at 18.2 MB in run-d68025a3c15c.
Step 52: a CRC32C name hash
hash mixes the name’s length with its first and last 8-byte windows through SSE4.2’s CRC32C
instruction, _mm_crc32_u64, instead of rotating the last window, combining it with the first by
XOR and multiplying: the length is the CRC’s starting state, and each window is one step, so a name
of under 8 bytes takes one step and a longer name two. The interner takes its slot from the CRC’s
top 14 bits, 18 to 31. LLVM knows the CRC to be under 2^32, so the probe still needs no bounds
check. In a simulation of the 16,384-slot table, 1.9 to 2.5% of lines take a second probe instead of
1.9 to 2.3% (seeds 1, 3 and 5), and 2.2 to 3.0% with the CRC’s low 14 bits. Seed 1’s share grows most,
1.9 → 2.5%, and its branch-misses:u with it, by 0.02 M.
Local, AC power, turbo off. perf stat, 30 interleaved runs: instructions:u 600.9 → 591.7 M
(-1.5%), cycles:u median 328.8 → 324.1 M (-1.4%), branch-misses:u 0.898 → 0.916 M,
L1-dcache-load-misses:u 3.95 → 3.98 M. ab.py, 61 interleaved runs, four rounds: medians
19.01 → 18.84, 18.92 → 18.78, 19.06 → 18.85 and 19.24 → 19.20 ms; seven earlier rounds of builds
with the same .text as steps 51 and 52 (three of 41 runs, four of 61): 19.12 → 18.97,
19.11 → 18.86, 18.96 → 18.80, 19.03 → 18.96, 19.05 → 18.85, 19.03 → 18.87 and 19.62 → 19.04 ms.
memory.peak, three batches of alternating rounds on seeds 1, 2, 3, 5, 7, 10 and 11 (3, 8 and 10
rounds): medians 18.21 → 18.41, 18.27 → 18.37 and 18.26 → 18.16 MB, where two more builds with the
same .text as the two drew 18.24 and 18.21 MB: noise, as the hash allocates nothing. S 373 → 372.
Gate: 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; clippy reports no
warnings.
Step 53: 9 fewer lines in the hour pass
Four rewrites in the hour pass and the work closure’s tail:
- The scatter takes a record’s latency bits unless they hold
LARGE, and the next large latency inunwrap_or_elsewhen they do, instead of a four-linematch: 3 lines. summarize_hourtakes only the endpoints with lines from the order, with afilter, instead of wrapping the loop’s body in anif: 2 lines.- The three selections of a large group are one
mapover (start, rank) pairs, each selecting in the suffix that starts at the rank before: 3 lines. - The work closure frees its chunk’s records and large latencies in one
map: 1 line.
With the filter or the map, LLVM no longer inlines percentiles into the work closure. It
becomes a function of its own, 21.7 KB with the networks, and the work closure is inlined into
fan_out instead. Either rewrite alone, and both together, run the same 3.6 M instructions:u
more, so that is the cost of the new layout, and it costs no cycles: perf stat, 10 interleaved
rounds of 3 runs, instructions:u 598.8 → 602.4 M, cycles:u median 330.0 → 330.4 M.
#[inline(always)] on percentiles, one line back, moved summarize_hour out of line instead
and timed the same.
ab.py, 61 interleaved runs, eight rounds against step 51: medians 19.03 → 18.94,
18.91 → 18.84, 19.01 → 19.04, 19.02 → 18.98, 19.05 → 19.00, 19.04 → 19.03, 19.06 → 18.96 and
19.11 → 19.01 ms (-0.3% on average), minimums 18.53 → 18.32, 18.39 → 18.35, 18.27 → 18.45,
18.41 → 18.37, 18.49 → 18.40, 18.65 → 18.54, 18.65 → 18.53 and 18.53 → 18.31 ms. memory.peak,
five alternating rounds on seeds 1, 2, 3, 5, 7, 10 and 11, three times: medians 18.17 → 18.28,
18.05 → 18.09 and 18.29 → 18.23 MB, from the same allocations. S 373 → 364. Gate: 310 pass,
0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; clippy reports no warnings.
Step 54: the latency’s space bounded
latency returns the index of the line’s last space, and the parse reads the status at space - 3
and ends the name at space - 4. On the fast path the space lies 1 to 8 bytes below the LF, from
byte 31 on. The slow path, for 8 to 10 digits, now lifts it to at least 4, which only a malformed
line can need. std::hint::assert_unchecked hands the parse that range, 4..LINE, and LLVM drops
the bounds checks of the status’s byte and of the name’s end: 3.1 instructions fewer per line.
Local, AC power, turbo off, on step 53’s code. perf stat, 30 interleaved runs: instructions:u
595.2 → 585.4 M (-1.6%), cycles:u median 321.2 → 320.9 M, L1-dcache-load-misses:u 3.98 → 3.98 M.
ab.py, 61 interleaved runs, six rounds: medians 18.92 → 18.88, 18.80 → 18.77, 18.84 → 18.79,
18.89 → 18.79, 18.86 → 18.81 and 18.79 → 18.75 ms, -0.05 ms (-0.3%) on average. On step 52’s code,
before step 53 went in, the same change ran instructions:u 591.5 → 581.8 M and cycles:u
324.3 → 322.3 M, and -0.11 ms (-0.6%) on average in eleven rounds of 61 runs (listed with the
pointer form under “Experiments that did not stay”). memory.peak, eight alternating rounds on seeds
1, 2, 3, 5, 7, 10 and 11: median 18.26 → 18.30 MB, noise, as the change allocates nothing.
S 363 → 364. Gate: 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; clippy
reports no warnings.
Step 55: 3 fewer lines
parse becomes an unsafe fn. Its # Safety section states what its assert! checked: its lines
end at least LINE bytes before the end of the log, as the padding from map_file provides. The
one call says why that holds: every chunk ends by len, LINE bytes before the end.
Two checks of input the spec rules out go to the indexes behind them. hour_index no longer checks
the hour against the span: an hour of the span’s days outside it now stops the run at the plan’s
index into the hours instead of at the parse’s expect. Interner::insert no longer asserts that a
4,097th name has no room: the index of its padded copy stops the run instead. Tried with hand-made
logs, each run ends with “index out of bounds” and writes no output: a line at 17:00 on the first
day, one at 18:00 on the last, and 4,100 distinct endpoints. A day outside the span still ends at
the expect.
Local, AC power, turbo off. perf stat, 30 interleaved runs, against step 54: instructions:u
585.39 → 585.41 M, cycles:u median 322.2 → 320.6 M. ab.py, 61 interleaved runs, fourteen rounds:
medians 18.76 → 18.78, 18.77 → 18.76, 18.80 → 18.80, 18.79 → 18.99, 18.70 → 18.88, 18.84 → 18.83,
18.85 → 18.88, 18.82 → 18.73, 18.84 → 18.78, 18.83 → 18.74, 18.80 → 18.73, 18.76 → 18.76 and
18.76 → 18.73 ms, and 23.94 → 23.67 ms in a round on a busy box: no change. .text, .data and
.bss keep their sizes, .rodata loses 96 bytes of panic messages, and no allocation changes.
S 364 → 361. Gate: 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; clippy
reports no warnings.
Step 56: 6 fewer lines
format_hourwrites a line’s six numbers with onemapinstead of aforloop: 2 lines, with the same machine code.- The work closure’s two counters come from one
[0; 2].map(AtomicUsize::new)on the line that namesallandsorted, withfinishedrenameddoneso that the line fits: 1 line. - The format queue no longer collects the hours into a
Vec<&Hour>. The output’s length and each hour’s place read the hour’sOnceLockwithwait, which returns at once, since every hour is done by the barrier: 1 line. summarize_hourbuilds each run’s iterator over its large latencies in theforheader: 1 line, with the same machine code.summarize_hourplaces the latencies in the whole buffer instead of a slice of the hour’s length: 1 line. On step 45’s code this cost 3% (see “Line cuts that moved the hour pass’s code” below); here, beside the other four cuts,ab.pymedians went 18.83 → 18.90, 18.87 → 18.84, 18.80 → 18.79 and 18.88 → 18.85 ms (61 interleaved runs, four rounds).
perf stat, 10 interleaved rounds of 3 runs: instructions:u 593.1 → 593.3 M, cycles:u median
327.2 → 325.8 M. ab.py, 61 interleaved runs, six rounds against step 53, two of them under
outside load: medians 18.74 → 18.66, 18.79 → 18.84, 18.51 → 18.55, 19.10 → 19.07,
18.81 → 18.72 and 18.82 → 18.81 ms (-0.1% on average). memory.peak, alternating rounds on
seeds 1, 2, 3, 5, 7, 10 and 11, medians: 18.24 → 18.17, 18.19 → 18.33 and 18.23 → 18.33 MB in
five rounds each, 18.29 → 18.28 and 18.32 → 18.28 MB in ten; the one allocation that changes is
the queue’s 576-byte vector, which goes. S 361 → 355 (on step 53’s code, 363 → 357). Gate: 310 pass, 0 fail; full seeds 1 to 7
and 10 to 12 give the reference hashes; clippy reports no warnings.
The board’s run of steps 54 to 56 together, run-c0db6c54d9a4 (commit ace82cf), drew 22.5 ms, a
slow draw: locally, step 56’s binary ran a median of 18.84 ms against step 53’s 18.87 (ab.py, 82
interleaved runs), and in the same run track D’s unchanged code drew 127.8 ms, against 122 to 127.
A second run of the same code, run-e31417916add (commit e7e0423, which changed only PERF.md files),
drew 17.65 ms, 18.6 MB and 86.3 points, and a third, run-2b07a12535b3 (commit 1534f22, which
changed only track B), 17.33 ms, 18.8 MB and 86.5 points, and a fourth, run-63683fcc0a53 (commit
f073734, which changed only track C), 17.26 ms, 18.2 MB and 86.7 points.
Step 57: threads started by one helper
Since step 14 the threads started as a tree: each handed the upper half of its numbers to a new
thread until it kept one, so the last of twelve started after four spawns. Now thread 0 spawns one
helper, which spawns threads 2 to 11 one after another and then works as thread 1. fan_out goes,
and each thread gets its own copy of the work closure, which holds only references. With one
hardware thread, the helper spawns nothing and does no work.
The last thread starts no sooner: phase timestamps (41 runs, two rounds) put its start 1.38 and 1.45 ms after the fork with the tree and at 1.48 and 1.49 ms with the helper. But each thread’s parse took 8.53 and 8.51 ms instead of 8.91 and 8.86 (medians), and the last parse ended at 9.98 and 9.94 ms instead of 10.21 and 10.19. The difference is the interner’s lock: a thread that finds it taken spins briefly and then sleeps. A build that counts inserts found the lock taken at 700 and 712 of a run’s 1,858 inserts with the tree, and at 336 and 248 of about 1,850 with the helper (means of 20 runs, twice). All inserts came in the first 1.4 ms, while the threads still met new names. With the helper, thread 0 starts after one spawn instead of three and has the table to itself for about 0.3 ms, in which it adds about half the names; with the tree, three more threads started while it had added fewer than a third. In two runs of a build that timestamps each thread’s progress, thread 0 took 0.62 and 1.19 ms over its first 4,096 lines with the tree, against 0.29 and 0.31 ms with the helper.
Local, AC power, turbo off, on step 56’s code. perf stat -r 20, twice: context switches 494 → 268
and 467 → 271. perf stat, 30 interleaved runs: instructions:u 585.53 → 585.52 M, cycles:u
321.4 → 318.5 M, cycles:k 113.6 → 112.0 M. ab.py, 61 interleaved runs, eight rounds: medians
18.71 → 18.48, 18.75 → 18.60, 18.67 → 18.38, 18.75 → 18.49, 18.59 → 18.39, 18.80 → 18.56,
18.83 → 18.52 and, under outside load, 23.30 → 22.91 ms: -0.24 ms (-1.3%) on average over the first
seven. The same code before its comment was written, whose panic messages name other lines, measured
-0.26 ms on average in eight more rounds. memory.peak, alternating rounds on seeds 1, 2, 3, 5, 7, 10
and 11, medians: 18.26 → 18.51, 18.40 → 18.48, 18.27 → 18.47 and 18.32 → 18.42 MB in four, six, ten
and ten rounds, and for the same code before its comment 18.18 → 18.18, 18.40 → 18.42 and
18.32 → 18.41 MB in three of them: about 0.1 MB more, worth about 0.2% of T, though every allocation
is the same. S 355 → 353. Gate: 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference
hashes; clippy reports no warnings.
Step 58: each line’s id settled one line late
A profile of step 57 (local, AC power, turbo off, seed 1; perf record of cycles, eight runs) put
43% of the cycles in parse, and 27% of its samples on the vpmovmskb right after the compare that
loads the slot’s padded copy, 6% more on the test after the slot load. The two loads depend on each
other: the slot’s index comes from the CRC, the copy’s address from the slot. Precise samples of
mem_load_retired.l1_miss put an L1 miss on the slot load for 34% of lines and on the copy’s two
halves for 25% and 20%, nearly all L2 hits (144,000 L2 misses a run in all). Each hyperthread has
half of the core’s reorder buffer, about two and a half lines of this loop, so a line whose two
loads missed one after the other could not retire, and the lines behind it waited.
Now the loop loads the slot of a line’s name as soon as the hash is known, and carries it to the
next iteration with the name, the 64 bytes from it, the slot’s index and the record without its id.
That iteration first does the next line’s front half (its LF, latency, status, name, hash and slot
load) and only then compares the carried name with the padded copy its slot names, and stores its
record. intern takes the slot and the content loaded from it instead of the hash; a second probe
loads the next slot as before. When insert finds that another thread filled the slot first, it
probes on from that slot with its new content instead of hashing the name again: the slots before
it on the name’s path hold other names for good. So does the next line when it has the same new
name, since its slot was loaded before this thread filled it. The first line of a chunk has no line
before it to finish, and the last is finished after the loop.
Local, AC power, turbo off, seed 1. perf stat, three interleaved rounds of 10 runs: instructions:u
583.5 → 627.6 M (14 per line more), cycles:u 319.2, 322.3 and 319.9 → 307.1, 310.5 and 308.4 M
(-3.6%), cycles:k and branch-misses:u unchanged. Top-down (10 runs): retiring 54.5 → 59.8% of the
slots, backend-bound 22.2 → 18.0%. perf record: samples at the copy’s compare 27 → 6% of the
parse’s, after the slot load 6 → 3%. Phase timestamps (41 runs): each thread’s parse took about
8.4 to 8.7 → 7.9 to 8.2 ms (per-thread medians), and the plan reached the threads at 11.22 to 11.27 →
10.90 to 10.97 ms after the fork. ab.py, 61 interleaved runs, seven rounds, the first four on the
same loop before insert lost its second hash: medians 18.53 → 18.09, 18.51 → 18.02,
18.97 → 18.55 and 19.01 → 18.69 ms, and under outside load 19.40 → 18.79, 19.47 → 18.91 and
19.41 → 19.03 ms: -0.46 ms (-2.4%) on average. memory.peak, three alternating rounds on seeds 1, 3
and 5: median 16.9 → 16.9 MB. S 353 → 361. Gate: 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give
the reference hashes; clippy reports no warnings.
Step 59: the interner released after the name sort
Nothing reads the interner after the plan: the parse is over, the names’ slices are copied into
the plan, and the sort is the last reader of the padded copies and the name table. The thread that
sorts now releases the whole static with release, about 0.2 MiB of touched pages (the 64 KiB of
slots, the 116 KiB of copies and the name table’s 1,858 entries). The release lands about 0.2 ms
into the hour pass, before each worker’s first hour has filled its buffer, which is when memory
peaks (step 34). One madvise call: one TLB shootdown for the other threads, which are counting.
Local, AC power, turbo off. memory.peak, alternating runs: seed 1, 20 and 15 rounds, means
16.77 → 16.59 and 16.69 → 16.51 MB (medians 16.75 → 16.65 and 16.6 → 16.5); seed 3, 15 rounds,
17.21 → 16.85 (median 17.2 → 16.8); seed 5, 15 rounds, 17.05 → 16.93 (median 17.0 → 17.0): about
-0.2 MB. ab.py, 41 interleaved runs, two rounds, under outside load (load average about 3.5):
medians 18.69 → 18.77 and 18.73 → 18.72 ms, minimums 18.15 → 18.26 and 18.11 → 18.06 ms. S 361 →
362. Gate: 310 pass, 0 fail; clippy reports no warnings.
Step 60: the input unmapped once the parse is over
A profile of step 59 (local, turbo off, seed 1; perf record -g of user and kernel cycles, eight
runs) put 32% of all samples in the kernel: page faults 20% (the input’s 6 to 8, the output’s 6, the
records’ 2), madvise 7.8% and the TLB-shootdown interrupts it sends 1.3%. Most of it is work per
4 KB page that the program cannot shrink: a 12-thread test that only maps the 239 MB file and
releases it spent 1.25 ms per thread on the faults and 0.6 ms on the release, whether the pages
were hot or cold. Two things around it were not fixed costs. The input’s page tables, 0.4 MB of
kernel memory that MADV_DONTNEED leaves in place, stayed until the exit, so they counted in the
hour pass’s peak. And the exit, on one thread inside the timed window, walked them and freed them.
Now each thread releases its share of the input right after its parse instead of after formatting,
and once every parse is done (the barrier) thread 1 unmaps the whole input with one munmap. Its
pages are gone by then, so the call only frees the page tables: 9 µs per thread on average, about
0.11 ms on thread 1, which the hour pass’s shared queue balances out. Nothing reads the log after
the parse, because the interner now keeps a copy of each name (Box::leak in insert, 1,842
small allocations under the lock it already holds), which the sort and the formatting read.
VmPTE at the plan: 668 → 272 kB.
Phase timestamps (31 interleaved runs, medians): the last parse and its release end at 10.00 ms
after the start of main, against 9.31 ms for the parse alone (the release costs a little more
while other threads still parse); the last thread finishes formatting at 16.11 ms, where its
input’s release used to end (16.13 ms); and the wall clock is 0.12 ms shorter, which leaves the
exit, no longer walking and freeing the input’s page tables. Local, turbo off. ab.py, 61
interleaved runs: seed 1, medians 18.45 → 18.45 and 18.51 → 18.36 ms, minimums 18.13 → 17.73 and
17.99 → 17.94 ms (and 18.68 → 18.36 ms in a round of 41); seed 3, 18.63 → 18.48, 18.74 → 18.61
and 18.81 → 18.59 ms, minimums 17.68 → 17.81, 18.02 → 17.82 and 18.02 → 17.63 ms; seed 5,
19.01 → 18.85 and 19.01 → 18.75 ms, minimums 18.22 → 18.19 and 18.45 → 18.11 ms; seed 7,
18.62 → 18.53 and 18.63 → 18.56 ms, minimums 17.94 → 17.77 and 18.14 → 17.93 ms; seed 1 again,
18.37 → 18.30 ms: -0.15 ms (-0.8%) on average over the eleven rounds. perf stat (10 runs, twice, interleaved): instructions:u 627.7 → 631.3 M,
cycles:u 308.4 and 308.1 → 317.5 and 312.9 M, cycles:k 119.7 → 127.2 and 124.2 M, context
switches 264 and 284 → 426 and 368. memory.peak, alternating runs: seed 1, 16.60 → 16.27 MB (6
rounds) and 16.54 → 16.18 MB (8 rounds, the same code before its comments); seed 3, 17.02 → 16.48
MB (6 rounds); seed 5, 17.00 → 16.33 MB (6 rounds); seed 7, 16.55 → 16.37 MB (6 rounds): about
-0.4 MB. S 362 → 364. Gate: 310 pass,
0 fail; clippy reports no warnings.
Step 61: a 20-bit latency field
What is live at the peak, on step 60’s code (local, turbo off, seed 1). Copies that exit at chosen
points, timed by the same systemd-run memory.peak, 15 alternating rounds: 15.70 MB when every
parse is done, 16.09 MB after the first 12 hours, 16.22 MB for the whole run. A copy of
/proc/self/smaps when every parse is done: 13,216 kB of anonymous memory, 12,488 kB of it the
records (12,109 kB) and the lists of large latencies (about 314 kB), 244 kB the interner’s .data;
VmPTE 676 kB, 272 kB after the unmap. With about 0.2 MB of kernel stacks that is 13.8 MB in use
against a peak of 15.7 MB: the rest is the kernel’s charge batches, 64 pages at a time per
CPU, of which each of the twelve CPUs keeps the unused part, so memory.current reads up to 3 MiB
above the pages in use in every phase alike. The records are three quarters of the peak.
A record spent 12 bits on the endpoint’s id, room for 4,096 names, but the spec fixes every seed’s
catalogue at exactly 1,842 (§2), which 11 bits hold. The freed bit goes to the latency: with 20 bits
a record keeps every latency under 1.05 s, and the lists of large latencies shrink from 2.59 to
1.18% of the lines on seed 1, 4.42 to 2.09% on seed 3, 4.08 to 1.86% on seed 5 and 1.94 to 0.89% on
seed 7: 0.17, 0.28, 0.27 and 0.13 MiB fewer pages from the parse to the end of the hour pass. The
interner’s names and padded copies, indexed by id, shrink to 2,048 entries (.data 426 → 249 KB,
the same pages touched), and a 2,049th name still stops the program at the index of its copy. Only
constants change, so S does not.
Local, turbo off. memory.peak, 5 alternating rounds each: seed 1 16.18 → 15.98 MB, seed 3 16.54 →
16.14, seed 5 16.50 → 16.08, seed 7 15.98 → 15.90: -0.28 MB (-1.7%) on average. ab.py, 61
interleaved runs: seed 1 medians 18.39 → 18.40 and 18.56 → 18.56 ms, seed 3 18.65 → 18.57 and
18.68 → 18.56 ms, seed 5 18.82 → 18.74 ms, seed 7 18.50 → 18.59 ms (-0.03 ms on average; a seventh
round under outside load left out). S 364 → 364. Gate: 310 pass, 0 fail; clippy reports no
warnings.
The same stop points after the change (seed 1, 10 rounds): 15.53 MB when every parse is done, 15.75 after 12 hours, 16.07 after 24 and 16.02 for the whole run. The peak is now the second round of hours: each worker’s buffer has grown to its second hour (29,000 to 39,700 lines, against 18,300 to 23,700 in the first), and the output lines of 24 hours, about 40 KB each, are held, while only the first round’s records have been freed.
Step 62: 20-byte output lines
After step 61 the peak is the hour pass’s second round, which holds the output lines of every hour
done so far. A line kept six u32: the endpoint’s id, the request count, the three percentiles and
the error count. The id has 11 bits (step 61), and a count fits in the other 21: the most popular
endpoint draws about 12% of the 3.1 million lines (Zipf, §2), and seed 1’s largest hour has 73,244.
So the two share one u32, and a line takes 20 bytes instead of 24: with 1,500 to 1,800 lines an
hour, about 0.15 MB less after 24 hours, and 0.5 MB less once all 72 wait for the formatting. The
code lines stay the same, with a shift and a mask.
Local, turbo off. memory.peak against step 61, two sets of 5 alternating rounds: seed 1 16.10 →
15.72 and 16.10 → 15.98 MB, seed 3 16.16 → 16.16 and 16.00 → 16.16, seed 5 16.14 → 15.94 and
16.18 → 15.90, seed 7 16.08 → 15.94 and 15.94 → 15.88: -0.13 MB (-0.8%) on average, nothing on seed
3. ab.py, 61 interleaved runs, nine rounds (the first four on the same code before a comment was
reflowed): seed 1 medians 18.59 → 18.83, 18.56 → 18.51 and 18.44 → 18.36 ms, seed 3 18.56 → 18.47
and 18.54 → 18.47, seed 5 18.60 → 18.56 and 18.70 → 18.72, seed 7 18.72 → 18.57 and 18.60 → 18.60:
-0.02 ms on average. S 364 → 364. Gate: 310 pass, 0 fail; clippy reports no warnings.
Step 63: 18 fewer lines
- The interner’s tables are four statics,
SLOTS,NAMES,PADDEDandCOUNT, instead of the fields of one staticInterner, andinternandinsertare plain functions instead of its methods. The struct’s definition, its initializer, which listed every field again, and theimplblock go;Paddednow holds theUnsafeCelland carries theSyncpromise, and the leader releases the three tables one by one. WithoutENDPOINTS., the parse’sfinishclosure fits on one line: 11 lines in all.Cargo.tomldrops thelarge_stack_arraysexception, which clippy no longer needs, and whose comment named the interner’s long-gone heap slots. The slots and the padded copies are all zeros, so they move from.datato.bss(.data255 → 58 KB,.bss24 → 220 KB).parseis the same machine code apart from the tables’ addresses,percentilesandput_numberare byte-identical, and the work closure differs in the leader’s two extrareleasecalls and in a few register and stack-slot choices. sort_networkcalls its seven merge levels through a local one-line macro,merge_levels!(1 2 3 4 5 6 7): a level is a const generic argument, which a loop cannot supply. 5 lines, and.textis byte-identical.inserttests the slot it loads withif let value @ 1..instead of binding it on a line of its own: 1 line, and.textis byte-identical.- The Dockerfile’s build stage runs
cd /src && cargo buildinstead of settingWORKDIR: 1 line. Built in the pinnedrustimage, the binary is still a plain static executable (ELF type 2), so.cargo/config.tomlstill applies; with--manifest-pathfrom/instead, it came out a static PIE (type 3).
Local, turbo off, against step 62. perf stat, 8 interleaved rounds of 5 runs, seed 1:
instructions:u 631.58 → 631.35 M, cycles:u median 313.2 → 311.9 M (6 of the 8 rounds lower).
ab.py, 61 interleaved runs, three rounds per seed: seed 1 medians 18.30 → 18.25, 18.36 → 18.31
and 18.36 → 18.34 ms (minimums 17.74 → 17.61, 17.77 → 17.64 and 17.86 → 17.82), seed 3
18.41 → 18.44, 18.39 → 18.32 and 18.50 → 18.45 ms (minimums 17.87 → 17.71, 17.83 → 17.81 and
17.83 → 17.92): -0.04 ms (-0.2%) on average. memory.peak, 5 alternating rounds: seed 1 median
15.8 → 15.8 MB, seed 3 16.2 → 15.9 MB. S 364 → 346 (Rust 358 → 341, Dockerfile 6 → 5). Gate:
310 pass, 0 fail; cargo fmt --check and clippy report nothing.
Step 64: 2 fewer lines
- The leader releases
SLOTS,NAMESandPADDEDin one statement,let _ = (release(&SLOTS), release(&NAMES), release(&PADDED));, instead of three: rustfmt keeps the tuple on one line (52 characters, under its width of 60).objdump -dof the whole binary is identical to step 63’s (.text994,455 bytes), so T and M cannot move. S 346 → 344. Gate: 310 pass, 0 fail;cargo fmt --checkand clippy report nothing.
Experiments that did not stay
-
stagefolded intomerge(local, turbo off, on step 62’s code), 3 lines fewer: with the stage’s loop inside the level’s, LLVM no longer unrolled every level for a constantm, andpercentilescame out inlined into asummarize_hourof its own (19.6 KB, against 21.7 KB).perf stat, two interleaved rounds of 5 runs: instructions:u 631.3 → 649.5 M, cycles:u 307.1 → 319.3 M. Not kept. -
Line cuts that rustfmt undoes (on step 62’s code), each spread back over more lines than it saved: one
useline for all ofstd::sync(nested braces go vertical), the parse’sChunkbuilt as one struct literal (a literal’s fields wider than 18 characters go vertical), the slot’s load written into the tuple that carries a line to the next iteration, and the two prefetches as onemapover[384, 448](calls, tuples and chains wider than 60 characters go vertical; the baremapalso tripsunused_must_use). -
Where the hour pass’s excess comes from, and an in-place sort, not built (on step 61’s code, from seed 1’s hour sizes and the stop points above). Smallest first in rounds of twelve, round k holds its buffers, about its hours’ size S_k in records, and the lines of every hour done so far, less the records of the rounds before it: 250,049 lines in round 1, 416,539 in round 2 against 250,049 freed, and about 40 KB of lines per hour on top. An in-place sort of each worker’s first hour would leave round 2 as high as it is (at most 0.36 MB off); in place for every hour, about 1 MB, it needs an in-place permutation across an hour’s runs in different chunks and each large latency paired with its endpoint, tens of lines against 6% of M. Two scatter passes of half the endpoints each, to halve every buffer: one more read of every record, about the count pass’s 3.5% of the samples, for 0.65 MB. Not built.
-
Pages that two finished runs share, released once both hours are done (simulated on seed 1’s runs in the kept order). A run’s release frees only the pages wholly inside it, so a page shared with a run of another hour stays until formatting. Pages whose every run is done but which are still held: 21 after 12 hours, 72 after 24 (0.08 and 0.28 MiB), 291 after all 72 (1.14 MiB). At the peak, between 12 and 24 hours, under 0.3 MiB, for the bookkeeping of which neighbouring runs are done. Not built.
-
Each thread unmapping its own share of the input after its parse (local, turbo off, on step 59’s code, names copied as in step 60).
munmapholds the address space’s lock, in read mode while it frees the pages, so the twelve calls queued behind each other: 2.8 ms per call on average, the last parse ended at 14.65 ms instead of 9.03 ms, andab.pymedians went 18.37 → 22.79 and 18.39 → 22.73 ms (61 runs, two rounds), for 0.74 MB less memory.peak. With each share released byMADV_DONTNEEDfirst, so that eachmunmaponly frees page tables:ab.pymedian 18.55 → 18.70 and 18.58 → 18.75 ms (+0.9%), memory.peak -0.14 and -0.27 MB. Splitting the input’s one mapping stalls the page faults of the threads still parsing it. Step 60 unmaps once, after the barrier. The release after the parse alone, without anymunmap: medians 18.44 → 18.41 and 18.58 → 18.49 ms, memory.peak unchanged. Not kept. -
The input read with
preadinstead of mapped (a 12-thread test in C, not built into the program): each thread reading its 20 MB share in 64 KB blocks into a buffer and touching every cache line took 6.87 ms; mapping it and touching every cache line took 6.3 ms, plus 0.6 ms to release it. Both stream at about 38 GB/s, so the faults are not the bound, and the copy would not overlap with the parse the way the mapped reads do. Not built. -
The hour pass without its record releases (local, turbo off, on step 59’s code), to bound what batching them could save:
release(&records[..0]),ab.pymedian 18.56 → 18.43 ms (-0.7%, 41 runs). The 222 calls that free pages each interrupt the other eleven threads, but the records of an hour lie in about three runs in different chunks, so they cannot be freed in fewer calls without the 4.9 MB that keeping them costs. Not built. -
The chunk’s records released before the output is mapped, not after (local, turbo off, on step 60’s code), so that eleven threads release while one maps:
ab.pymedians 18.51 → 18.50, 18.57 → 18.44 and 18.58 → 18.60 ms (61 runs, three rounds). Not kept. -
The latency buffer allocated before the first barrier instead of after the plan (local, turbo off, on step 60’s code), so that its
mmapfalls in the wait for the slowest parse rather than at the hour pass’s start, where twelve such calls and the input’smunmapqueue for the address space’s lock:ab.pymedians 18.73 → 18.75 and 18.64 → 18.67 ms (61 runs, seeds 1 and 3). Not kept. -
One malloc arena for all threads (
mallopt(M_ARENA_MAX, 1), 2 lines, local, turbo off, on step 60’s code), to spare the twelve arenas’mmap,munmapandmprotectcalls, about 40 sleeps on the address space’s lock a run (perf recordof context switches):ab.pymedians 18.47 → 19.16 and 18.61 → 19.30 ms (+3.7%), memory.peak 16.33 → 16.13 MB (6 rounds). Not kept. -
Each hour’s place in the output populated with
MADV_POPULATE_WRITEbefore it is formatted (local, turbo off, on step 60’s code), to replace 35 page faults an hour with one call:ab.pymedians 18.51 → 19.19 and 18.63 → 19.35 ms (+3.8%, 61 runs, seeds 1 and 3). Not kept. -
The name’s copy made before
inserttakes the lock (local, turbo off, on step 60’s code), so that the lock is not held throughmalloc: context switches 391 → 329 (perf stat, 10 runs), cycles:u unchanged,ab.pymedians 18.44 → 18.41 and 18.65 → 18.59 ms. 1 line. Not kept. -
MADV_SEQUENTIALon the input (local, turbo off, on step 60’s code), so that its release skips marking each page accessed: cycles:k 124.9 → 122.8 M (perf stat, 10 runs), page faults unchanged,ab.pymedians 18.62 → 18.58 and 18.65 → 18.71 ms. 1 line. Not kept. -
Each hour’s lines released once formatted, again (local, turbo off, on step 60’s code): memory.peak 16.22 → 16.17 MB (6 rounds). The hour pass’s start still sets the peak. Not timed.
-
Where the kernel’s time goes, at step 59 (
perf record -g, eight runs): of the output’s page faults (6.1% of all samples), 1.1% is threads spinning on the file’s page-cache lock inshmem_add_to_page_cache, since all twelve add pages to one file at once; nothing in user space changes that short of fewer threads formatting. The input’s faults spend 2.9% innext_uptodate_folio, which reads each page’sstruct pagewhile it maps 16 pages per fault. -
The input released once a thread’s hours are done, before the second barrier (local, turbo off, on step 58’s code), to use the wait for the slowest worker:
ab.py, 41 interleaved runs, median 18.81 → 19.66 ms (+4.5%). The release’s shootdowns reach the workers still in the hour pass, and every name read while formatting faults its page in again. Not kept. -
Each hour’s whole output pages released once formatted (local, turbo off, on step 59’s code), so that the exit has fewer of the output’s page-table entries to clear:
ab.py, 61 interleaved runs, three rounds, medians 18.91 → 19.42, 18.81 → 19.05 and 18.96 → 19.29 ms (+1.9%), and 4 lines more. The 72madvisecalls interrupt the formatting threads with shootdowns. Not kept. -
Thread 0 spinning until every thread is done, instead of sleeping in the scope’s join (local, turbo off, on step 59’s code), so that the exit need not wake it:
ab.py, 41 interleaved runs, medians 18.74 → 18.63 and 18.66 → 18.84 ms. No difference beyond the noise, for 3 lines. Not kept. -
percentilesinlined into the hour pass (#[inline(always)], local, turbo off, on step 58’s code): instructions:u +0.8 M, cycles:u 309.3, 312.0 and 306.9 M against 305.3, 310.7 and 307.2 M. Not kept. In step 58’s profile (5 runs, call graphs),percentilesis 8.9% of all samples, 5.9 of them the selections for groups over 128 values, 2.5 the networks; the count and the scatter are 3.5 and 5.7%; page faults are 20.4% (input 5.8, the output’s shmem pages 4.9, records and buffers 3.3, the rest entry and locking) andmadvise8.1%. -
Other hour orders, simulated (seed 1’s hour sizes, time proportional to lines): the kept order ends 0.10 ms after largest first (4.35 against 4.25 ms per worker); ascending to the 30th hour, then descending, then the 12 smallest, ends at 4.28 ms. At most 0.4% of T, less than the run to run spread of the workers’ last hour (0.7 ms between the first and the last worker, phase timestamps). Not built.
-
Other ways to settle the id late (local, AC power, turbo off, on step 57’s code;
perf stat, 10 runs, interleaved with step 58’s loop where two numbers are given). The front half as a function that returns the whole next line in anOption, carried bywhile let: 712 M instructions:u and 322 M cycles:u against step 57’s 583 and 318 M (as a closure, which LLVM did not inline, 772 M). The slot hashed again insideinternon every line: 665 M and 313 M. The slot only prefetched a line ahead and loaded just before the compare,internunchanged: 646 M and 310 to 312 M against 626 M and 306 to 308 M. The padded copy also prefetched once its slot was loaded: 633 M and 309 to 310 M against 306 to 307 M. The status and the latency stored at once and the id ORed into the record a line later: 0.6 M instructions fewer, cycles:u 305 to 311 M against 306 to 309 M, andab.py(41 runs) 18.22 against 18.12 ms. The slot hashed again only on the rare path, withinterntaking the slot’s content alone: 626.5 M, the same cycles,intern7 lines longer, andab.pymedians 18.20 and 18.12 against 18.09 and 18.02 ms (61 runs, two rounds). Not kept. -
16-bit slots, on step 58’s loop (local, turbo off): instructions:u +3.7 M, cycles:u 306.8 and 309.5 M against 305.4 and 307.5 M (
perf stat, 10 runs, interleaved). Not kept. -
One input prefetch per line instead of two (local, turbo off, on step 58’s code): instructions:u -3.1 M, cycles:u 312 to 314 M against 306 to 310 M (
perf stat, 10 runs, interleaved). Not kept. -
Each thread’s chunk mapped with
MADV_POPULATE_READbefore its parse (local, turbo off, on step 58’s loop): cycles:u -0.8%, butab.py, 41 interleaved runs: median 17.99 → 18.62 ms (+3.5%), since each thread maps all of its 20 MB before it parses a line. Not kept. -
The scatter’s destination prefetched 16 records ahead (local, turbo off, on step 58’s code): instructions:u +31 M, cycles:u 308.0 and 307.5 M against 308.9 and 306.4 M. Not kept.
-
Measured, not built (local, on step 58’s code). About 2,800 TLB-shootdown interrupts reach CPUs 0 to 11 per run (
/proc/interrupts), some 230 per thread, most of them from the hour pass’s per-run record releases; step 45’s notes put what dropping those releases saves at 0.8 to 1.5%, for 4.9 MB more.available_parallelismtakes 55 µs before the first spawn, reading the cgroup’s CPU quota as well as the affinity mask;sched_getaffinityalone would start too many threads on a box that limits CPUs by quota. Creating and mapping the output takes 44 µs between the second barrier and the first hour’s formatting. Per run, the last parse ends 0.15 ms after the mean of all twelve (10.73 against 10.58 ms, medians of 41 runs), which bounds any static reweighting of the chunks. -
Other ways to start the threads (local, AC power, turbo off, on step 56’s code;
ab.py, 61 interleaved runs, medians against step 56). All eleven spawned by thread 0, 3 lines fewer than step 57: +0.24 to +0.45 ms in six rounds (+1.7%), since thread 0 began its own parse only after eleven spawns. A helper that only spawns, with thread 0 working meanwhile, so that 13 threads run for a moment, also 3 lines fewer: -0.24 to +0.57 ms in six rounds, -0.01 ms on average. The helper spawning threads 11 down to 2: -0.28 ms on average in eight rounds, and two helpers that spawn half of the threads each, 2 lines more: -0.26 ms, against -0.26 ms for step 57’s helper in the same rounds, so the order made no difference beyond the noise. Not kept. -
The interner’s lock taken by spinning (local, AC power, turbo off, on step 56’s code):
try_lockin a loop withspin_loopinstead oflock, which spins briefly and then sleeps.ab.py, 61 interleaved runs, six rounds: medians +0.74 to +1.00 ms with the tree, and +0.05 to +0.16 ms with step 57’s helper against the helper alone. Not kept. -
The output written with
pwrite(local, AC power, turbo off, on step 56’s code). With the file’s size set as now, every thread opened the file for itself and wrote its hours through aBufWriterof 16 or 64 KB, seeking to each hour’s place: no page faults on the output and nothing to unmap at exit, which phase timestamps put at 0.55 ms betweenexitand the parent’swait, against 0.74 and 0.79 ms. But tmpfs takes the file’s lock for every write, so the threads’ writes queued behind each other: formatting took 3.30 and 3.32 ms per thread instead of 1.60 and 1.62 (64 KB buffers, 41 runs, two rounds).ab.py, 61 interleaved runs, six rounds: medians +1.43 to +1.62 ms with 64 KB buffers (+8.1%) and +1.63 to +2.13 ms with 16 KB (+9.4%). memory.peak, four alternating rounds on seeds 1, 2, 3, 5, 7, 10 and 11: median 18.18 → 18.39 MB. Not kept. -
The latency’s digits masked from the space itself (local, AC power, turbo off, on step 55’s code and on step 56’s):
latencykeeps the digits above the last space with0x0F0F_0F0F_0F0F_0F00 << (8 * last_space)instead of0x0F0F_0F0F_0F0F_0F0F << (8 * (last_space + 1)): the mask’s lowest byte is already zero, so the shift needs no+ 1. On step 55’s code, one instruction fewer per line, instructions:u 583.6 → 580.3 M, but cycles:u 318.3 → 320.7 M (perf stat, 40 interleaved runs).ab.py, 61 interleaved runs, medians against step 55: +0.02, +0.02, 0, +0.03, -0.07, +0.02, -0.06, +0.03, +0.02 and -0.03 ms (ten rounds); against step 56: +0.07, -0.08, +0.18, -0.03, -0.03 and +0.23 ms (six rounds). Not kept. -
The last hours handed out largest first (local, AC power, turbo off, on step 57’s code). The plan’s order ends with the
threadssmallest hours, smallest first; reversed, 1 line more, a worker that frees up early takes the larger of them, as in largest-first scheduling.ab.py, 61 interleaved runs, seven rounds and an eighth under outside load left out: medians -0.11 to +0.03 ms, -0.04 ms on average. Phase timestamps (41 runs, two rounds) put the hour pass, from the plan to the barrier, at 4.25 and 4.21 ms against 4.23 and 4.24, and the spread of the workers’ last hour ends at 0.27 and 0.24 ms against 0.28 and 0.28: the tail is set by the size of the last hours, not their order. The last 24 hours largest first, 2 lines more: -0.01 to +0.03 ms. Not kept. -
The records written through a pointer (local, AC power, turbo off, on step 52’s code). The parse writes each record at
get_unchecked_mut(count)and counts up. A pointer that moves up one record per line, with a closure that turns it back into a count for the runs and the final length, took 2 lines more and anunsafewrite. Alone it saved 3.0 M instructions:u (591.5 → 588.5 M) and 0.2 M cycles:u (324.3 → 324.1 M); on top of step 54’s bound, 3.1 M instructions and 1.2 M cycles more (581.8 → 578.7 M and 322.3 → 321.1 M;perf stat, 30 interleaved runs).ab.py, 61 interleaved runs, eleven rounds, step 52 / the bound / the bound and the pointer: medians 18.86 / 18.79 / 18.70, 18.87 / 18.83 / 18.75, 18.85 / 18.75 / 18.75, 18.94 / 18.81 / 18.78, 18.85 / 18.80 / 18.82, 19.00 / 18.84 / 18.69, 18.89 / 18.72 / 18.70, 18.95 / 18.82 / 18.85, 18.96 / 18.81 / 18.82, 18.83 / 18.71 / 18.63 and 18.78 / 18.68 / 18.64 ms. On average the bound gained 0.11 ms (0.6%) for its line, and the pointer 0.04 ms (0.2%) more for its two, about what two lines cost. -
fan_outas a binomial tree (local, turbo off, on step 53’s code): threadtstartst + 1,t + 2,t + 4and so on above2t, which needs no ranges: 6 lines instead of 8. The last of twelve threads still starts after four spawns, but thread 0 makes four spawns before its own parse instead of three.ab.py, 61 interleaved runs, four rounds: medians 18.92 → 18.97, 18.37 → 18.58, 18.78 → 18.89 and 18.80 → 18.91 ms (+0.6%). Not kept. -
The network’s functions without
#[target_feature]:target-cpu=alderlakeenables AVX2 for the whole crate, but rustc still counts a call to an AVX2 intrinsic as unsafe unless the calling function has the attribute itself (“the context requires the following additional target feature: avx2”), so the three attributes stay. -
Selection for every group, without the networks (local, turbo off, on step 50’s code):
percentileswith only its three selections, andsort_network,merge,stageand their wildcard import deleted, S 379 → 334.ab.py, 61 interleaved runs: median 19.06 → 20.84 ms (+9.3%).perf stat, 4 interleaved rounds of 3 runs: instructions:u 598.9 → 649.8 M, cycles:u +12.8%. The 45 lines are worth about 3.6% of T. Not kept. -
The count pass as one
flat_mapover the runs (local, turbo off): 2 lines fewer than the nested loops. As aforover theflat_map, it ran 9.2 M instructions:u more (598.9 → 608.1 M), becausenextchecks for the end of the inner slice at every record. Asfor_each, which folds each run’s slice in a loop of its own, it ran the same instructions but measured slower on step 53’s code:ab.py, 101 interleaved runs, four rounds, medians 19.03 → 19.14, 19.06 → 19.06, 18.77 → 18.87 and 18.99 → 19.02 ms (+0.3%), and +0.2% in eight rounds of 61 runs beside step 51, more than the 0.16% its 2 lines are worth. Not kept. -
Counts and errors in one
u64per endpoint (local, turbo off, on step 50’s code): one read-modify-write per record in the count pass instead of two, with the errors in the upper half: 13.6 M instructions:u more, and no fewer cycles. Unchecked indexing in the count pass and the scatter: instructions:u -6.3%, cycles:u -1.1%, and no change inab.py. Both passes wait on memory, not on instructions. Not kept. -
Freeing more before the exit (local, turbo off, on step 50’s code). At
exit, the kernel still unmaps 11.2 MB of output mapping, about 4 MB of heap, mostly the hours’ lines in 12 malloc arenas, and 0.7 MB of page tables, on one thread inside the timed window: phase timestamps put 0.75 ms betweenexitand the parent’swait, against about 0.2 ms for an idle 12-thread process. Alone, it unmaps about 99 ns per output page and 250 ns per heap page; 12 threads unmapping in parallel took 190 to 437 ns per page each, and every call interrupts the other threads to flush their TLBs. Releasing each hour’s lines and its place in the output once it was formatted: medians +0.40 ms; its place only, +0.44 ms; its lines only, +0.18 ms. Each thread releasing its share of the output after its share of the input: -0.03 to -0.09 ms, about what its 3 to 4 lines cost; with the formatted lines released too, +0.07 to +0.11 ms. Finished threads spinning until the last one callsexit, instead of returning: +0.08 ms. The format queue in largest-first order: no change; with the finished hours’ output released through a shared cursor as well: +0.04 to +0.06 ms. Not kept. -
put_numberinlined, with its eight- to ten-digit path in a#[cold]function (local, turbo off, on step 49’s code and on step 50’s).put_numberwrites a value of eight digits or more by calling itself for the leading digits. That call keeps it out of line, and every call, however short its number, pushes and pops three registers and loads five 64-bit constants: 761,448 calls on seed 1, of which 1,836 have eight digits or more. With that path in a#[cold]put_large,put_numberis inlined at its six uses informat_hour, and the constants stay in registers: instructions:u 616.0 → 602.8 M on step 49 and 598.9 → 585.8 M on step 50, but cycles:u medians 337.8 → 337.9 M and 332.7 → 329.8 M (perf stat, 10 interleaved rounds of 3 runs).ab.py, 61 interleaved runs, four rounds: medians 19.39 → 19.41, 19.34 → 19.35, 19.36 → 19.34 and 19.34 → 19.37 ms on step 49, and 19.09 → 19.05, 19.08 → 18.95, 19.14 → 19.02 and 19.03 → 19.05 ms on step 50: -0.35% on average there and +0.05% on step 49, against the 0.3% that its 4 lines cost. Kept out of line by#[inline(never)]instead, it saved 7.6 M instructions:u on step 45 and no cycles:u (on battery, not comparable). Not kept. -
Other selections for the groups over 128 (microbenchmark, one thread, ns per group for 129 to 256 / 257 to 1,024 / over 1,024 values). The current chain: 1,035 / 2,087 / 8,655. A radix select on a log-scale key, a histogram and then the same chain on the candidate buckets: 1,109 to 1,422 / 2,332 to 3,355 / 10,601 to 10,711. Two pivots from a 64-value sample around each rank, one pass that copies the values between them, and a select on those: 4,119 / 6,891 / 26,216, against 1,464 / 2,997 / 12,365 for the chain in the same runs (on battery, not comparable).
sort_unstabletook 13.3 ns per value against 4.6, and an AVX2 quickselect 2.53 ns per value against std’s 2.21 for the median of the largest groups. A 256-value network took 803 ns against 1,038 for 129 to 256 values: 0.35 ms of one thread’s time over seed 1’s 1,477 such groups, about 0.15% of T, less than its 2 lines cost. Not kept. -
Other number formatting (local, turbo off). Two digit groups in one
u128: format 1.60 → 2.22 ms per thread. Lines built straight in their place instead of on the stack: no change (microbenchmark, 41.4 against 41.3 ns per line). Name bytes from the padded copies: 0.1 ms per thread less, butformat_hourthen needs the interner, and the longer signature and copy cost 5 lines afterrustfmt. Withput_largeabove, on step 45’s code (on battery, not comparable): the digits split out ofeight_asciibefore the'0'offset is added saved 1.6 M instructions:u more for 2 more lines; a fixed 128-byte copy of the name, read past its end in the padded input mapping, saved 0.3 M instructions:u for 1 line; and the width as2 + (value | 1).ilog10()cost 2 M instructions:u more. Not kept. -
Slots of 16 bits (local, turbo off, on step 45’s code): an id needs 12, so
AtomicU16slots halve the table to 16 KB.ab.py, 41 interleaved runs, two rounds: medians 20.25 → 20.44 and 20.19 → 20.38 ms. Not kept. -
Padded copies indexed by slot instead of by id (battery, on step 45’s code): a probe compares the window with the copy at its own slot, without loading the id first, and the hour pass maps ids to slots. The copies then take 512 KB, 128 pages, against 256 KB: DTLB misses that hit the STLB 1.9 → 4.8 M a run, and cycles:u +1.5 to 2%. Not kept.
-
The record written through a moving pointer instead of at
records[count](battery, on an early form of step 46): 3.0 M instructions fewer, no fewer cycles, for 2 more lines. Not kept. -
The status bit and the latency merged into one value before the lookup (battery, on an early form of step 46): 6.3 M instructions more. Not kept.
-
Hours summarized during the parse, for a lower peak (local, turbo off, on step 45’s code). The log went out in 72 pieces of about an hour each, in file order. An hour was summarized and its records freed as soon as every piece from the one before its first line to the one after its last was parsed; a line arriving after its hour was done would have rerun the program without early hours (never tested). Each hour’s lines were freed once it was formatted. On full seeds 1 to 7 and 10 to 12, 62 hours went early and the output matched. memory.peak on seed 1, 5 alternating rounds: 17,444 to 18,280 → 15,112 to 15,672 KiB. The peak moved to the end of formatting (15.2 MB, 9.9 of it output), and the parse alone climbed steadily to 13.3 MB, because three things stayed: the 12 latency buffers, about 280 KB each and now touched during the parse, the lines of the hours done so far, and the pages that two runs share.
ab.py, 61 interleaved runs on seed 1, medians / minimums: 20.27 / 19.72 → 21.48 / 20.81 ms and 20.18 / 19.71 → 21.48 / 21.02 ms (+6%).perf stat -r 8, twice: instructions:u 633.6 → 631.3 M, cycles:u 336 to 337 → 339 to 342 M, cycles:k 77 to 78 → 80 to 82 M, so the work grew about 2% and the rest was waiting. Phase timestamps: threads finished their last piece between 12.5 and 15.0 ms and waited for the last one, 0.8 ms each on average against 0.42 ms at the parse barrier, and with only the 10 hours left after the parse for 12 threads, each sat idle 0.56 ms on average, against 0.3 ms at the end of the full hour pass. S 361 → 461. Not kept. -
Keeping each run’s records until the hour pass ends (local, turbo off, on step 45’s code). Deleting
release(records)after each run’s scatter insummarize_hour, one line fewer, cost 2.3%:ab.py, 61 interleaved runs, two rounds, medians 20.25 → 20.68 and 20.33 → 20.78 ms. The frees were not the cause. The work closure grew from 0x40ba to 0x40fb bytes and every spill offset moved, the parse loop’s too, so cycles:u rose 2 to 4% (perf stat -r 9, twice: 367 to 373 → 381 to 382 M) while cycles:k fell 5%. Keeping the call asrelease(&records[..0])frees nothing and leaves the closure’s size and address as they were:ab.pymedians 20.25 → 19.96 and 20.08 → 19.93 ms (61 runs) and 20.17 → 20.14 and 20.39 → 20.03 ms (41 runs), 0.8 to 1.5% faster, with cycles:k -2.7%. But memory.peak on seeds 1, 2, 3, 5, 7, 10 and 11, five rounds, went 18.15 → 23.06 MB (+4.9 MB): about a point lost, against 0.09 to 0.16 gained from T. Releasing only runs of at least 4 or 8 pages kept memory.peak within 0.16 MB (18.26 → 18.42 MB, same seeds, four rounds), but it moved the closure again, to 0x4145 bytes:ab.py, 41 runs, two rounds, medians +0.2 to +0.6 ms. Few of the calls free anything: seed 1 has 1,065 runs, and only 222 of them hold a whole page, though those hold 98% of the records. For the othersmadvisegets no page and returns without interrupting the other threads. Not kept. -
#![no_main]and a static interner, for an earlier start (local, turbo off, on step 45’s code).#![no_main], with anextern "C" fn main, skips std’s start-up, which reads/proc/self/mapsand sets up signal stacks. The static interner kept its three tables in statics instead of on the heap.ab.py, 61 interleaved runs, four rounds, mean change of the medians: -0.02 ms for#![no_main], 0 for the static interner and -0.06 ms for both. Phase timestamps (21 runs, two rounds) putmain94 µs sooner and the threads’ median start 0.16 ms sooner, but the last parse ended no sooner: 11.95 → 12.00 and 11.82 → 11.83 ms. Start-up savings barely reach the barrier: until a thread starts, its SMT sibling has the core to itself, so only about a quarter of a start delay shows at the barrier. Not kept. -
A lock-free
insert(local, turbo off, on step 45’s code): a new name took its id with afetch_add, wrote its padded copy and its name, then claimed its slot with a compare-exchange and probed again if another thread had filled it first. The insert mutex costs a thread up to 0.4 ms of waiting, about 3 ms summed over a run. Without it, context switches went from about 340 to 118 (perf stat -r 11, twice) and cycles:k fell 3.5%, and phase timestamps put the parse’s end 0.15 to 0.2 ms sooner. The wall did not follow:ab.py, 61 interleaved runs, four rounds, medians 20.25 → 20.26, 20.23 → 20.23, 20.13 → 20.12 and 20.23 → 20.28 ms. A timer that measures fork to wait as the board does, withoutab.py’s extratasksetexec, gave 19.11 → 19.18, 19.01 → 19.17 and 19.29 → 19.33 ms (61 runs, three rounds). Not kept. -
No barrier before the output is mapped (one line fewer: the first thread done with its hours waits for each hour’s
OnceLockinstead). On step 39’s PIE build,ab.pymedians went 20.92 → 20.44 and 20.80 → 20.31 ms, but phase timestamps put only 20 µs of that in the wait and 0.5 ms in the parse:Barrier::wait, left with one caller, was inlined into the work closure, and the parse loop inlined there came out with a different register allocation. On step 41’s static build the same change cost 0.6 ms (medians 20.33 → 20.98 and 20.35 → 20.93 ms). Not kept. -
Line cuts that moved the hour pass’s code (local,
ab.py, 40 runs, two rounds): an empty group skipped withlet [_, ..] = group else { continue }, the hour’s buffer used without re-slicing it to the hour, and the network’s run lengths taken from aforover(1..).map(|s| 1 << s). Each moved the network’s code by 14 to 268 bytes, and each cost about 3%: medians 19.98 → 20.52 to 20.58 and 19.93 → 20.53 to 20.61 ms. A fresh copy of the unchanged binary timed the same as the original (medians 20.20 → 20.28 and 21.06 → 20.57 ms), so it is the code’s placement, not its page-cache copy. Setting the network’s first partner distance with its run length, one line fewer, moved no permute but measured slower in all four numbers (medians 20.40 → 20.42 and 20.22 → 20.26 ms, minimums 19.68 → 19.80 and 19.79 → 19.83 ms), so it stayed out too. -
PGO (local, turbo off, on step 41’s code): a profile from three runs on each of full seeds 2 to 4, passed as
-C profile-use, with every function matching it.ab.py, 61 interleaved runs, medians / minimums: 20.27 / 19.62 → 20.54 / 19.98 ms and 20.03 / 19.55 → 20.26 / 19.75 ms on seed 1; 20.18 / 19.70 → 20.48 / 20.00 ms and 20.34 / 19.75 → 20.66 / 20.13 ms on seed 10, which it was not trained on.perf stat -r 5, twice: instructions:u 690 → 662 M, cycles:u 359 to 361 → 370 to 378 M, branch-misses:u 1.10 → 1.20 M. -
Pieces handed out from a shared counter instead of one fixed chunk per thread (local, turbo off, on AC): with 16 pieces per thread the median went 30.68 → 31.54 ms, with 64 pieces to 33.78 ms.
perf statshowed 3.5% more cycles for the same instructions and 11% more dTLB misses. On battery power, where some threads started 4 to 8 ms late, the pieces helped. -
Releasing the input inside the hour pass instead of after formatting (local, turbo off): 3 ms slower. Freeing pages interrupts every other thread of the process to flush its TLB.
-
Sorting small groups instead of selecting (n ≤ 16 or ≤ 32; local, turbo off): medians 34.53 to 34.61 ms, no better than selection.
-
Compact copies of endpoint names for the interner (local only, turbo off): the idea was that comparing against a name’s first occurrence in the 239 MB file costs a cache miss on most lines. Measured: parse loop 18.3 ms per thread before and after. The miss was not the cost. Reverted.
-
Per-thread
MADV_POPULATE_READof each chunk before parsing (local only, measured under heavy load from other jobs, so only indicative): 80.5 → 80.1 ms. Not kept. -
Loops on 64-byte boundaries (
-C llvm-args=-align-loops=64, as track B builds; local, on step 45’s code):ab.py, 40 interleaved runs, two rounds, medians / minimums 20.22 / 19.46 → 20.87 / 20.22 ms and 20.37 / 19.61 → 20.99 / 20.35 ms. The output hash is unchanged. -
Where memory.peak comes from, at step 57 (local, seed 1, a copy that reads its cgroup’s memory.current and memory.stat in a loop on a 13th CPU, five runs; systemd-run’s peak for the unchanged binary: 16.7 to 17.2 MiB). memory.current moves in steps of 0.25 MiB, the 64 pages that the kernel charges at a time and keeps per CPU, so it reads up to 3 MiB above the pages in use. At the end of the parse it reads 14.8 to 15.8 MiB: 13,064 KiB of anonymous memory (12,144 of it records, 244 the interner’s
.data) and 1.07 MiB of kernel memory (0.70 page tables, mostly the input’s). Within 0.4 ms of the hour pass’s start it peaks at 16.8 to 17.4 MiB: each worker’s first hour (18,300 to 23,700 lines) scatters into fresh buffer pages before any record is freed, about 1 MiB in all, 1.0 to 1.6 MiB above the parse’s end. Formatting ends at 15.8 to 16.8 MiB: the 10.1 MB output, 4.1 MiB of anonymous memory (2.9 of it the hours’ lines) and the kernel’s 1.1. So the records set a floor of about 15 to 15.8 MiB under any order of the work. The cheap cuts in reach: the 12 smallest hours first, about 0.25 MiB off the spike, for a later tail; the interner’s slots and padded copies released after the name sort, 0.18 MiB; each hour’s lines released once formatted, which only matters once the spike is gone and cost 0.18 ms before. A counting sort holds its source and its destination at once, so removing the spike needs an in-place sort of each first hour. Not built. -
Where step 63’s time goes (local, seed 1, a copy that stamps
CLOCK_MONOTONICandru_minfltat each phase of each thread;perf record -c 200000with the samples binned by those stamps). See the profile notes. Every idea below aims at a piece of that timeline, and none reached 0.8%. -
The latency buffers leaked (no
munmapwhen a thread ends; local, on step 63’s code):ab.py, 61 interleaved runs, seed 1, medians 18.22 → 18.20 ms and 18.51 → 18.51 ms. The process exit unmaps them anyway, and the exit is on the critical path either way. Not kept. -
Each place’s output released after the format loop (
MADV_DONTNEEDon the shared output mapping): 18.45 → 18.67 ms. The release sends TLB-shootdown IPIs to every thread still formatting. Not kept. -
A final barrier, then each thread releasing 1/12 of the output so the exit tears down a mostly empty mapping: the exit call to the parent’s
waitfalls from 0.576 to 0.356 ms, but the 12 simultaneous slice releases take 0.089 ms undermmap_lockand IPI contention, and the barrier waits for the slowest formatter.ab.py, 61 runs, four rounds: seed 1 18.47 → 18.34, 18.40 → 18.44 and 18.51 → 18.38 ms, seed 3 18.50 → 18.35 ms (-0.09 ms, -0.5%, on average), for 4 to 5 more lines. Not kept. -
The input released after the first barrier, the last releaser unmapping it (instead of each thread releasing its share straight after its parse): 18.43 → 18.56 and 18.39 → 18.61 ms. A release right after a parse overlaps its SMT sibling’s parse (kernel work against compute); 12 releases at once contend on the same locks. Not kept.
-
128-byte padded copies in the interner (so names up to 127 bytes compare without
memcmp): cycles:u +1% in interleavedperf stat; the extra 64 bytes per line cost more than the rare long-namememcmpsaves. Not kept. -
Two 64-byte tables for long names (the second 64 bytes of a name in a table of its own): instructions:u -12.6 M, cycles:u -0.8%, but
ab.pyseed 1 18.49 → 18.45 ms and seed 3 18.38 → 18.48 ms, for 4 more lines. Not kept. -
Each thread’s latency buffer allocated before its parse (its
mmapaway from the input’smunmapand the shared release): seed 3 18.62 → 18.76 ms. Not kept. -
Not built, bounded by the timeline: stealing release work from the slowest parser (all of the first barrier’s mean wait is 0.157 ms), mapping the output before the hour pass (map_output takes 0.05 ms), and a SIMD
put_number(the formatting’s user time is 1.2 ms of the 1.55 ms phase; the rest is the kernel’s shmem faults andxa_lock). -
Two of the step 57 notes’ memory cuts, after step 64 (local, turbo off). (1) The interner’s three tables released before the names’ output order is sorted, the sort comparing the names the plan already holds instead of the padded copies; (2) the hour order’s last
2 × threadshours reversed instead of thethreadssmallest moved to the end. memory.peak, 6 alternating rounds on seeds 1, 3 and 5: median 15.90 MB for step 64, 15.95 with both cuts, 16.00 with a third that wrote the output from the buffer’s end. Within the noise of the kernel’s charge batches; not kept.
Profile notes
- Phase split after step 1b (native, turbo off): parse loop 18.3 ms per thread (finding line ends
alone 6.9 ms, interning about 8, record push about 7), endpoint merge 1 ms, hour pass 13 ms,
output write 4 ms, and about 8 ms outside
main. - Unmapping the input at exit, timed with an explicit
munmap: 3.9 ms on one thread. perf recordafter step 2: parse loop 37% of cycles,Interner::intern14%,select_nth_unstable11%, hour-pass loop 9%, libcmemcmp/memcpyabout 9%.- Timeline of step 63 (local, seed 1, a stamped copy, per-thread medians in ms from
main‘s start, 12 threads on 0-11): parse 8.6 (spread 0.40 across threads), share released 0.7, wait at the first barrier 0.157 on average, the leader’s plan 0.06 (it ends 0.006 after the last release), unmap and latency buffer about 0.1, hour pass 4.0 (threads end within 0.29 of each other), latencies released, wait at the second barrier 0.141,map_output0.05,relchk0.04, formatting 1.55 (end spread 0.07), then the exit call to the parent’swait0.55. Kernel share of each phase (perf, cycles per run): parse 26% (next_uptodate_folio, fault-around), share release 100% (unmap_page_range), hour pass 21% (TLB-shootdown IPIs from the other threads’ releases, first-touch faults), output placement 99% (IPIs, spinlocks), formatting 47% (shmemfaults,xa_lockcontention inshmem_add_to_page_cache), exit 60 to 70% (osq_lock, IPIs). The waits at the two barriers and the leader’s serial plan add up to 0.36 ms (2.2%); the largest pieces left are the parse’s user time and its fault-around.
Track B: Index
Answer 50,000 queries over a corpus of about 250,000 documents. For each query, print how many documents match, the sum of their ids and the ten smallest ids. A query is either a boolean expression, evaluated strictly left to right, or an exact phrase.
| Reference | Mine | |
|---|---|---|
| Time, full dataset, seed 1 | 56.35 s | 87.3 ms |
| Peak memory | 2,200 MB | 42.1 MB |
| Code lines | 91 | 961 |
| Board points | 0 | 79.6 |
About 645 times the reference’s speed. B is the track I’d most like another shot at, and its PERF.md is the longest of my four logs, failed experiments and all.
Approach
flowchart LR
Q["queries.txt<br/>read first, as the spec allows"] --> T["term table<br/>one id per distinct query term"]
T --> S["sample the first 1/64 of<br/>the corpus: how rare is each term"]
S --> P["plan: triggers per query<br/>rarest term, or a bool cover"]
D["docs.txt<br/>mapped, 12 threads"] --> W["walk: AVX2, 64 bytes<br/>at a time, tokens per line"]
P --> C
W --> C["check each document<br/>against the queries it triggers"]
W --> B["set queries: a bitset per<br/>common term, an id list per rare one"]
B --> C
C --> M["merge per query<br/>counts, id sums, smallest ids"]
M --> O["results.txt"]
queries.txtis read before the corpus (spec §3 allows it), and every distinct query term gets a small id. From then on the corpus is indexed only for terms the queries use. 79% of the corpus’s tokens are query terms; the other 21% cost one hash lookup each and nothing more, and no posting list is ever written for a term no query mentions.- Tokenising the first 1/64 of the corpus estimates how many documents hold each term. Each query then gets triggers: terms such that every matching document contains at least one of them. A phrase uses its rarest term, and a boolean query uses a cover of its terms. Triggers only decide how much work gets done, so a bad estimate makes the run slower and can never change an answer.
- One pass over the corpus does the rest. Each thread scans a chunk of whole lines, and an AVX2 classifier turns every 64-byte block into three masks: token starts, token ends and line feeds. The token loop packs eight tokens at a time. At the end of each document, only the queries its triggers point at get checked, and only against that document. A phrase is checked at each position of its trigger term, and a boolean query takes one lookup in a truth table of which of its terms the document contains. Set operations done per document give the same answer as combining whole posting lists (spec §3).
- A boolean query whose cover has a common term in it would get checked in far too many documents, so those run on whole sets instead: a bitset per common term and an id list per rare one, window by window, merged at the end.
- Per query, the chunk counts and id sums add up, and the smallest ids come from the earliest chunks. Memory stays flat the whole way: per query a count, an id sum and the first matches, and per kept term one window of documents. No posting list for the whole corpus ever exists, which is how the peak stays at 42 MB next to the reference’s 2.2 GB.
Dependencies
No crates, only std.
cd track-b && cargo +1.99.1 build --release --offline
The build has one flag the other tracks don’t: every loop starts on a 64-byte boundary, so the pass’s hot loops keep their speed when a change somewhere else moves their function (PERF.md, step 21). Like A and C, it’s a plain static executable at a fixed address, with no dynamic loader and no position-independent code (PERF.md, step 30).
With another 24 hours
The pass costs about 113 instructions per token, and 49% of the cycles sit in the line-end closure that works through each line’s probe list (PERF.md, after step 63). Past that the time is spread thin, with no source line above 5.8% of the cycles. A third of the branch misses are the tokenizer’s loop exit, once per 64-byte block, which no history can predict. The start also leaves about 6 ms of the 12 CPUs idle; step 66 parallelised its largest piece, for 2.9% locally and 3.6% on the board.
The fastest B entries on the board run in about 62 to 66 ms, two of them in Rust, so my next day would go into a second design: collect each query term’s documents during the pass and answer the queries on those sets afterwards, instead of checking at every line end. Memory has nothing left to give: the final code’s runs use 41.8 to 42.2 MB, already under the 44 MB cap, so a smaller peak wouldn’t score anything.
Track B: performance log
Each kept step has the board run that measured it. Anything marked local was timed on my laptop (an i7-13620H with turbo off), two versions run side by side, and every experiment I reverted sits under the step it was tried after, with its numbers.
| Reference (step 0) | Final code (step 66), board run | |
|---|---|---|
| T | 56.35 s | 87.3 ms (run-33959bbbe488) |
| M | 2,200 MB | 42.1 MB |
| S (lines) | 91 | 961 |
| Points | 0 | 79.6 |
| Step | Change | Run ID | T (s) | M (MB) | Points |
|---|---|---|---|---|---|
| 0 | The reference, unchanged | 56.35 | 2200 | 0 | |
| 1 | Rust v1: queries read first; one parallel pass keeps postings for query terms only and checks phrase windows at each phrase’s trigger term | run-af10ba01e8f3 | 0.711 | 180.0 | 53.6 |
| 2 | Term keys read with one masked 32-byte load; tokens found 64 bytes at a time from AVX2 masks | run-03e880c5be0a | 0.5555 | 182.1 | 55.5 |
| 3 | Costly BOOL queries evaluated on per-chunk bitsets and id lists, the rest checked per document; one 16-byte prefetched probe per token; first matches grouped per thread | run-0ba4a60c4e07 | 0.4085 | 82.7 | 60.9 |
| 4 | Queries parsed on every thread into flat arrays; the plan’s per-term lists built with one counting sort | run-03f5349811b3 | 0.3798 | 70.7 | 62.1 |
| 5 | Queries on sets evaluated every 4,096 documents inside the pass; glibc’s mmap threshold fixed at 128 KiB | run-16bfddb1c5c1 | 0.3708 | 45.7 | 64.3 |
| 6 | Per-document BOOL queries compiled to 64-bit truth tables with one packed tally each, prefetched at the trigger term; term keys folded through a mask table | run-a7a48ad2968d | 0.2838 | 43.1 | 67.2 |
| 7 | Blocks of 2 MiB or more on transparent huge pages; a window’s id lists hold 16-bit offsets | run-91f41d207c31 | 0.2793 | 46.3 | 67.0 |
| 8 | Term table sized once from the queries’ term count, and its keys trimmed after the intern | run-533a441d6902 | 0.2705 | 45.1 | 67.5 |
| 9 | Tokens that are no query term take the id of a bit that is never set, so clearing the seen bits takes no branch | run-d85affefdce5 | 0.2679 | 44.2 | 67.7 |
| 10 | Only the term table on transparent huge pages, allocated alone at a 2 MiB boundary; the global allocator is gone | run-b4d6bfbdd0e9 | 0.2698 | 43.9 | 67.7 |
| 11 | A check’s cell takes a match with a conditional move instead of a branch | run-6a27aa29cd80 | 0.2644 | 44.9 | 67.8 |
| 12 | The corpus walk takes one callback per token and one per line end, so the per-token one is inlined | run-68a53e20303e | 0.2450 | 43.8 | 68.8 |
| 13 | A token’s hash multiplies the XOR of its key words once, instead of once per word | run-4a44efe39605 | 0.2403 | 43.4 | 69.0 |
| 14 | The per-document checks count a query’s first matches in a byte per query, not in its cell | run-f56225b92327 | 0.2350 | 45.1 | 69.1 |
| 15 | Memory at its peak: a thread frees its window before grouping its first matches, and the grouping keeps no second copy of the group starts | run-7458013fd46b | 0.2346 | 42.3 | 69.2 |
| 16 | The query and check cells are written when allocated, so the pass’s first store to a page no longer replaces the shared zero page and interrupts every core | run-6afbb627903d | 0.2343 | 42.0 | 69.2 |
| 17 | Each thread drops its chunk’s pages of the corpus mapping when its pass ends, instead of the exit unmapping all of them on one core after the output is written | run-bfce9886b69d | 0.2354 | 43.4 | 69.2 |
| 18 | A term table slot holds a term’s first 12 bytes instead of 8, so a token of 9 to 12 bytes no longer loads its term’s key from a second array | run-e847cb4a493b | 0.2208 | 41.8 | 69.9 |
| 19 | 99 fewer code lines: the cold code and the term table simplified (no doubling), the walk’s bit pops in one helper; the key-mask table aligned to a cache line | run-74f2276732d6 | 0.2241 | 42.9 | 70.1 |
| 20 | The rarity sample is the corpus’s first 1/64 (4,005 documents on seed 1) instead of its first 1,000 documents, each thread counting a part | run-75d28a617cc4 | 0.2158 | 42.8 | 70.5 |
| 21 | 35 fewer code lines: one helper runs and joins each set of threads, the intern loop drops its prefetch, the output adds each query’s cells once; every loop starts on a 64-byte boundary | run-f0c533c66a88 | 0.2165 | 42.9 | 70.6 |
| 22 | 8 fewer code lines in code that runs once, with the same machine code | run-59d37d7b5803 | 0.2177 | 42.3 | 70.5 |
| 23 | A per-document check reads its terms’ bits with one AVX2 gather instead of six loads, and the document’s term bits are read and cleared without bounds checks | run-29bb809aa3f8 | 0.2048 | 43.5 | 71.2 |
| 24 | A document’s checks are listed one by one as its BOOL triggers appear, so one loop runs them all instead of one loop per trigger | run-170e5552bd10 | 0.2085 | 42.4 | 71.0 |
| 25 | The token loop takes no branch on what a token is: a token that is no query term probes to an empty slot, id 0, and a document’s new stored terms and BOOL triggers are listed by a store and an add | run-ab97ce51555f | 0.1746 | 43.5 | 72.9 |
| 26 | A document’s term bits are cleared by zeroing their words, a store with no load, and the probe’s end test is kept one branch by an empty asm block instead of black_box, which sent it through the stack | run-1d7859f315a0 | 0.1682 | 43.2 | 73.3 |
| 27 | Every thread plans a share of the queries, and the term table’s flags are added to every slot, an empty one adding 0, without a test for empty slots | run-fc3b46db2437 | 0.1650 | 41.7 | 73.5 |
| 28 | The rarity sample probes a line’s tokens at its end, as the pass does, and counts without a branch; interning a term takes no branch on whether it is new; the sample’s end is found without the other 63 cuts | run-75ef64ef4099 | 0.1643 | 42.2 | 73.5 |
| 29 | A query on sets adds its window’s matches in one vectorized sum instead of a call per word; a term’s store is a u32 code instead of an enum; the terms kept in rows and in lists are listed apart, so adding them takes no branch on which | run-575e79713710 | 0.1623 | 43.1 | 73.7 |
| 30 | A plain static executable (crt-static and relocation-model=static) instead of a dynamically linked PIE | run-4654d088e3bb | 0.1615 | 41.1 | 73.7 |
| 31 | The token loop writes a document’s term ids and its kept rows, lists and BOOL triggers into four runs of one slice, and its seen bits, without bounds checks, so its registers no longer spill | run-ea58cfb946e5 | 0.1483 | 42.1 | 74.6 |
| 32 | 1 fewer line with the same binary: the build stage mounts its sources instead of copying them | run-ced2f9ec7167 | 0.1491 | 41.1 | 74.6 |
| 33 | A document’s checks are added in one Tally method that takes no branch on a check’s result: the queries of the checks that the document is one of the first matches of are moved to the front of its list of checks, and only those go on to the first-match counts | run-94e224675c5a | 0.1455 | 41.3 | 74.8 |
| 34 | The term lookups take no bounds checks: the probe reads the slots unchecked from a key’s home slot on, the prefetches take pointers, and the token loop holds the term table and the seen bits as locals | run-401b90111691 | 0.1618 | 40.5 | 73.7 |
| 35 | 11% fewer instructions in the corpus pass: a document’s checks are written to a slice sized once and evaluated without bounds checks, the tokenizer picks the start of a token carried over from the previous block once per block, a key’s window takes one bounds check and its hash two words, phrases are compared inline, and a long key’s mark rides in its slot’s tail | run-8bf61f0fec95 | 0.1313 | 43.3 | 75.9 |
| 36 | The serial start about 2.2 ms shorter: the intern prefetches 16 keys ahead and keeps each term’s length and only the long terms’ keys, a term’s cost is computed where the planning reads it, the sample keeps each term’s count and last document in one cell, and the term table’s flags are collected in bytes | run-ce4c2e1d13c6 | 0.1342 | 42.8 | 75.7 |
| 37 | The term table’s huge pages asked for again: once the table is written, MADV_COLLAPSE collapses its 4 KiB pages into huge pages if its faults found no free one | run-5de0cb146d0e | 0.1445 | 41.4 | 74.8 |
| 38 | No frees once the output is formatted, as the plan and the chunks are ManuallyDrop, and the output’s numbers written by format_into instead of write! | run-5de0cb146d0e | 0.1445 | 41.4 | 74.8 |
| 39 | The per-document checks on huge pages of their own, as the term table’s slots are, through one helper; the rarity sample summed as each thread’s part comes in instead of after the last; the plan’s counting sort puts its items in from the back, so the starts need no rotation | run-8d0c750cfc9c | 0.1277 | 42.9 | 76.2 |
| 40 | The plan’s checks grouped on a thread of their own while the main thread groups the phrases, flags the terms, numbers the stores and marks the term table; a term’s BOOL flag comes from the checks it keys, not from their groups | run-ff1ae2c91791 | 0.1269 | 43.1 | 76.3 |
| 41 | 5.5% fewer instructions in the corpus pass: the walk keys and prefetches the tokens itself, into a buffer whose address and count stay in registers; a block’s token ends are taken one line at a time, split at its LFs by one mask, so the token loop tests no LF; a line’s id is left out at its end instead of tested for at each token; a key is folded in two vector operations instead of four | run-ff1ae2c91791 | 0.1269 | 43.1 | 76.3 |
| 42 | 7.1% fewer instructions in the corpus pass: the walk’s token loop runs in a call of its own per line, so the line end no longer holds the registers it needs, and a key’s 32-byte window is tested against a bound held in a register | run-b96f907a19fc | 0.1151 | 41.2 | 77.2 |
| 43 | A phrase candidate is first tested on one more of the phrase’s terms, which the plan keeps beside the trigger, before the phrase’s terms are loaded: 97.5% of the candidates stop there | run-b96f907a19fc | 0.1151 | 41.2 | 77.2 |
| 44 | The line end’s token loop prefetches each token’s entry of check_at, which the BOOL triggers’ loop reads at random, one token ahead of that loop | run-0f0011884453 | 0.1166 | 42.4 | 77.1 |
| 45 | A token whose home slot holds another term stops there unless the slot is marked as the home of a term stored further on; a key’s long bit is its byte 12’s bit 5, moved by one shift | run-636a838e4422 | 0.1135 | 42.3 | 77.3 |
| 46 | A window’s matches counted and summed four words at a time from two nibble tables, instead of six masked popcounts per word | run-f954cb1f35f8 | 0.1117 | 43.3 | 77.4 |
| 47 | A document’s phrase triggers are listed in a fifth run of the token loop’s slice, by a store and an add, instead of pushed to a Vec behind a branch | run-f954cb1f35f8 | 0.1117 | 43.3 | 77.4 |
| 48 | Memory: a chunk’s first matches kept as query indices, each doc’s followed by its id, 4 bytes per match instead of 8; the long terms’ keys kept off transparent huge pages | run-f91848d73390 | 0.1134 | 37.6 | 77.2 |
| 49 | Step 48’s first-match list undone, since B’s memory sits at the cap; the long terms’ keys stay off huge pages, and a term is common from one sampled document in 48 instead of 32 | run-ec587c6dcef4 | 0.1131 | 41.7 | 77.3 |
| 50 | A token’s probe carries its home slot’s address instead of its index, and a probe past its home slot runs out of line, so the line end’s token loop holds no register for the term table and keeps two values on the stack instead of four | run-086c324cb377 | 0.1064 | 41.2 | 77.9 |
| 51 | A probe compares a short key’s bytes 8 to 11 with its slot’s tail as they are, without building the long bit, which only a key past 12 bytes, on its own branch, needs | run-086c324cb377 | 0.1064 | 41.2 | 77.9 |
| 52 | The line end sets a doc’s bits in its terms’ rows without bounds checks on the term’s store or the row | run-9069c200f6e8 | 0.1086 | 42.4 | 77.7 |
| 53 | 37 fewer code lines in code that runs once or once per thread, with the pass’s instructions unchanged | run-d502f3e18c27 | 0.1050 | 42.0 | 78.2 |
| 54 | The common terms take ids 1 up, the rows’ numbers, so a doc’s rows are the first words of its term bits: the line end copies those words, and every 64 docs a 64 × 64 bit transpose turns them into the rows’ words; the rows run of kept, its store lookups and the ROW flag go | run-255e2729d35b | 0.1011 | 42.0 | 78.5 |
| 55 | Reverted after three board runs (see its section). Trial: 11 threads parse the queries while the main thread counts their terms and sets up the term table, then interns each share as soon as it is parsed | run-dc45dd0a1279 | 0.1041 | 41.6 | 78.1 |
| 56 | Trial: the probe’s first test compares a key’s whole second word with the slot’s tail, so it takes no branch on a key’s length, and a term past 12 bytes is found past that test; the BOOL triggers’ loop reads check_at and writes todo without bounds checks | run-e8e81cdefaa9 | 0.0977 | 41.8 | 78.8 |
| 57 | The id lists’ entries pushed to the end of one log, and sorted into the lists by counting at each window’s flush, instead of pushed into one of 3,452 lists at random | run-e8e81cdefaa9 | 0.0977 | 41.8 | 78.8 |
| 58 | Trial: of the short terms whose home slot a slot is, the one with the most sample hits moves into it, on a thread of its own during the plan’s tail, so 44% fewer probes go past the home slot | run-f39c6987110f | 0.0981 | 42.3 | 78.6 |
| 59 | Trial: the probe’s first test branches on one select, the key’s difference kept only when the slot has MORE, and the token loop at the line end no longer prefetches each token’s check_at entry, so it keeps every address in a register | run-b6d1d5065964 | 0.0950 | 41.7 | 79.0 |
| 60 | While the main thread interns the terms, three threads read the corpus a byte per 64 KiB, so the scanning threads’ walks take no page faults on it; the chunks are freed on a thread of their own while the output is written | run-938dc27813b7 | 0.0952 | 41.3 | 79.0 |
| 61 | The line end’s token loop holds a zero in a register for its three selects, and the tokenizer takes a long token’s key on a cold branch, the mask’s address from the length negated, and a token’s start and end as offsets from its block: 3.9 fewer instructions per token | run-280052ffeb2c | 0.0979 | 41.8 | 78.6 |
| 62 | Reverted after two board runs (see its section). Trial: the line end’s token loop stores each token’s flags only, and a doc’s terms kept in lists, BOOL triggers and phrase triggers are packed into their runs 8 tokens at a time by a permutation table, 10 instructions fewer per token in the loop for 4.25 in the packing; a key’s home slot comes from its first word alone, two instructions fewer per token in the tokenizer | run-e89cc599f8ef | 0.1054 | 40.9 | 77.7 |
| 63 | Trial: step 62’s packing of a doc’s runs, 8 tokens at a time, with step 61’s hash of the key’s first two words | run-51792bbbc94f | 0.0929 | 41.9 | 79.1 |
| 64 | Reverted after one board run (see the not-kept list). Trial: the query terms interned on every thread into one shared table, a new term’s slot claimed by a compare-and-swap of its head and its id taken from a block of 64; the page-touching helpers moved into the plan’s tail | run-bb4ed7d47695 | 0.0934 | 41.7 | 78.8 |
| 65 | Reverted after two board runs (see the not-kept list). Trial, pushed as 052ab6e: 32-byte aligned checks, a branch-free add_checks and immediate vector shifts in pack, S 901 → 956 | run-e40ad8747964 | 0.0944 | 41.7 | 78.7 |
| 66 | Step 64’s parallel intern again, on step 63’s code (see its section) | run-33959bbbe488 | 0.0873 | 42.1 | 79.6 |
A second run of the step 1 code, run-85b6361ddf94, measured 0.703 s and 181.1 MB.
Step 24’s board run drew 208.5 ms, 1.8% slower than step 23’s 204.8 ms, although step 24 ran 2% faster locally in three rounds (its section has them). A second run of the step 24 code, run-6280980d331c, measured 202.0 ms and 43.5 MB (71.3 points). Draws of the same code vary on the board: step 21’s machine code measured 216.5 and 217.7 ms (rows 21 and 22).
Local numbers below come from 12 threads on the P-cores (CPUs 0-11, turbo off), full seed 1,
perf stat -r 5, with the variants interleaved over three rounds, unless a section says
otherwise.
Step 2: term lookup and tokenizer
- Lookup: term keys sit densely by id, and a token’s key is one 32-byte load from the mapped
file, masked to the token’s length and lowercased with a shift, instead of a
memcpyinto a zeroed buffer that the next load then stalled on. - Tokenizer: two AVX2 compares turn 64 bytes into a token-byte mask and an LF mask. Token
starts and ends are
token & !prevand!token & prev, walked withtrailing_zeros, so no loop looks at single bytes. Locally: 0.632 → 0.579 s, cycles 14.60 → 13.27 G.
Step 3: costly BOOL queries on sets, the rest per document
Seed 1 has 36.3 million tokens, and 79% of them are one of the 75,747 distinct query terms.
Step 2 appended every hit to a posting list (about 640,000 Vecs across the threads) and then
merged lists per query. The profile split evenly between the term lookup, the appends, and the
merges, and the lists set the 174 MB peak.
- 3a, two evaluation paths. Each BOOL query gets a cover: terms such that every matching document holds one of them. If the cover holds a common term (one in at least 1 in 32 sampled documents), the pass records the query’s terms as sets instead: a bit per document for common terms, an id list for rare ones. Those 1,772 queries are evaluated after the pass with word-wide AND, OR and AND-NOT, 64 documents per operation. The count is a popcount, and the id sum comes from six masked popcounts per word. The other 29,000 queries are checked at the end of each document that holds a cover term (17.4 million checks). Each check is a flat, self-contained program run against a per-document term bitset that fits in L1.
- 3a, one probe per token. Each slot of the term table (16 bytes) holds a term’s first 8 key bytes, its id, and flags saying what the pass does with it. A token thus costs one load, and only the rare term longer than 8 bytes reads the rest of its key. Each document’s probes are prefetched as it is tokenized and resolved at its LF, so the loads overlap instead of stalling one by one.
- 3b, first matches. Each thread groups its chunk’s first ten matches per query with a counting sort over the match counts it already keeps. This replaced one serial sort of 1.25 million (query, doc) pairs between the pass and the output.
Locally, step 2 → 3a → 3b: elapsed 0.584 to 0.592 → 0.469 to 0.534 → 0.427 to 0.429 s; cycles 13.28 to 13.56 → 9.97 to 10.08 → 10.04 to 10.09 G; memory.peak 173.3 → 82.1 → 79.7 MB. S went from 484 to 745.
Step 4: the serial start
Before the pass, one thread parsed the queries and built the plan while the other eleven waited: 56 to 59 ms of a 0.43 s run.
- Parse, 32 → 15 ms. Every thread parses a share of the query lines into flat arrays. One thread then gives each distinct term its id, in file order, so the ids do not depend on the thread count. It loads the table slot of the term 16 ahead while it interns one, so the cache misses overlap, and when the table doubles it is rebuilt from the keys in id order.
- Plan, 25 → 15 ms. A query’s terms and operators sit in flat arrays instead of two
Vecs per query. The phrases and checks each term triggers are collected as pairs and grouped by one counting sort, instead of aVecper term.
Locally, step 3 → 4: elapsed 0.4335 to 0.4380 → 0.3905 to 0.3929 s; cycles 9.97 to 10.05 → 9.84 to 9.87 G; memory.peak 79.2 → 69.2 MB. S went from 745 to 803.
Step 5: memory
At step 4 the peak was 15 MB of tables and plan, plus about 4.3 MB on each of the 12 threads. The biggest share was the bitset rows and id lists of the queries on sets, which each thread kept for its whole chunk.
- Sets per window. Each thread keeps those rows and lists for one window of 4,096 documents, and evaluates the 1,772 queries on sets at the window’s end. Their matches go to the same per-query tally as the other queries, so the output phase treats every query alike. The per-query “last matched document” array became a per-document list of matched phrases, and the term names are gone: a term’s cost reads its length from its key. Local: memory.peak 68.3 → 50.8 MB, cycles 9.91 to 9.97 → 9.85 to 9.91 G.
- A fixed mmap threshold. glibc raises its mmap threshold to the largest mapped block freed
so far, and parsing and planning free blocks of up to a few MB, so smaller blocks then come
from per-thread arenas and stay resident after they are freed. With
mallopt(M_MMAP_THRESHOLD, 128 KiB), every block of 128 KiB or more goes back to the kernel when it is freed, such as each thread’s first matches once they are grouped. In the first measurement: 50.8 to 51.2 → 42.4 to 45.3 MB at the same speed.
Locally, step 4 → 5, six interleaved rounds on a busy machine: cycles 9.74 to 9.89 → 9.73 to 9.89 G, elapsed 0.3926 → 0.3867 s in the quietest round; memory.peak 68.4 to 69.8 → 39.6 to 40.8 MB over five runs. S went from 803 to 790.
Step 6: checks without branches
Where step 5’s time went on seed 1, found by switching off one stage at a time:
| Stage | ms |
|---|---|
| Start-up on one thread: query parse 15 (11 of it interning terms), plan 15 | 30 |
| Tokenizer | 41 |
Each token’s key: the u128 masking took about 77 instructions a token, and key_in was not inlined | 36 |
| Hashing, prefetching and storing each token’s lookup for the line end | 19 |
| Term lookup at the line end (23 M branch misses) | 55 |
| Per-token bookkeeping, seen bits and flags (31 M branch misses) | 65 |
| Phrase checks | 7 |
| Per-document BOOL checks and their tallies: 17.5 M checks at about 160 cycles and 3 branch misses each | 132 |
Branch misses wasted 35% of all pipeline slots; waiting on memory, 5%. So the checks lost their branches first. Each change below is measured on top of the ones before it (medians, local, turbo off; step 5 ran 384 to 387 ms in the same sessions):
- Truth tables. Each per-document BOOL query has at most 6 distinct terms, so it compiles to a 64-bit truth table: its AND, OR and NOT applied to six fixed bit masks. The skip for documents already counted from an earlier cover term is folded into the table. A check is a shift and a mask. 350.5 ms; branch misses 117 → 80 M.
- One tally per check. Each check keeps its count and id sum in one u64 next to its neighbours, and the check and its tally are prefetched when the trigger term is first seen in a document. 320 ms.
- A mask table for the key fold. A sliding table of 0xFF bytes replaces the u128 shifts,
key_ininlines, and 2.2 G instructions disappear. 288.5 ms, but memory rose 8 to 10 MB. - The memory back. Each query keeps only its first ten matches, every per-query tally is
one u64 (
count << 40 | id sum), and the check tallies are freed before the grouping. 296.4 and 296.9 ms over two rounds of 11 runs (min 289.6). memory.peak 44.9 MB against 44.6 MB for step 5 (8 interleaved samples each, noise ±2 MB).
S 790 → 837. Gate: 507 pass, 0 fail. The packed sums limit the corpus to fewer than 2^20 documents; a larger one stops with an error, and the spec’s full scale has 250,000.
Tried and dropped: a parallel sampling pass (3 ms faster, inside the noise), and no cap on the first matches (5 ms faster, 2.7 MB more).
Step 7: huge pages
At step 6 the pass spent 7.5% of its cycles walking page tables: 18.7 million dTLB load
misses walked to completion, 541 M cycles with a walk under way. Each token probes the 4 MiB
term table at a random slot, and a long token then reads its full key from a 2.4 MB array.
On 4 KiB pages those tables span more pages than the TLB holds. The kernel here has
transparent huge pages set to always, but in the middle of a run only 2 MiB of the 18 MiB of
large blocks sat on huge pages: the blocks did not start on 2 MiB boundaries, and without
MADV_HUGEPAGE the kernel does not compact memory to find a huge page.
- A global allocator that gives every block of 2 MiB or more a 2 MiB alignment and calls
madvise(MADV_HUGEPAGE)on it. Smaller blocks, andreallocbetween small sizes, still go straight to glibc, which grows a large block withmremapinstead of copying it. Walks fell to 3.7 million and walk cycles to 142 M. - 16-bit window lists. A window spans 4,096 documents, so each document in one of its id
lists ([
Window]) fits in 16 bits as an offset from the window’s first document. This halves the lists of the queries on sets on every thread, and it takes back about 1.1 MB of the memory the huge pages add.
Locally, step 6 → 7, three interleaved rounds: cycles 7.07 to 7.23 → 6.89 to 7.01 G, task-clock 3,059 to 3,131 → 2,958 to 3,014 ms, elapsed 0.2997 to 0.3045 → 0.2838 to 0.2843 s in the two quiet rounds. Alternating runs, 20 each: median wall 295.2 → 285.3 ms. memory.peak over eight runs each: 41.1 to 44.2 → 40.2 to 45.1 MB (medians 41.9 and 43.3). S went from 837 to 871.
Step 8: the term table sized once
The intern grew the term table from 1,024 slots by doubling, which rebuilt it eight times. The table is now created with one slot per term occurrence in the queries, rounded up to a power of two (about 153K occurrences and 75.7K distinct terms on all seven seeds, so 262,144 slots, the size the doubling reached anyway). The intern drops from about 11 to 6.5 ms. The keys are trimmed to their length once the intern ends, since the spare capacity would stay resident on huge pages. The scan’s machine code is unchanged.
Local, the time from start to the end of planning, medians of 6 interleaved runs: 27.96 → 23.5 ms. User instructions 10.23 → 10.06 G. memory.peak 42.2 → 42.6 MB (noise about ±1 MB). S unchanged. Gate: 507 pass, 0 fail; full seeds 1 to 7 match.
What is left of start-up, and why it stays: query parsing 3 ms (already parallel), intern 6.3, sampling 5.6, the plan loop 5.3, grouping and marking 3.2. A parallel sample, mark and plan loop took start-up to 19.0 ms but added 55 lines, which costs more than it saves; a partitioned parallel intern would take about 45 lines for about 4 ms.
Step 9: one branch less per token
At each line end the pass clears the seen bit of every token’s term. A token that is no query
term, 21% of them, had the id u32::MAX and was skipped with a test. That test mispredicted:
7.8 M of the 76.6 M branch misses. Such a token now takes the id of the bit that pads the
checks, which is never set, so clearing it changes nothing and the loop has no branch.
Locally, on step 7 (the scan is the same at step 8): branch misses 76.6 → 68.8 M; over three interleaved rounds, cycles 7.07 to 7.10 → 6.81 to 6.84 G, task-clock 3,039 to 3,054 → 2,931 to 2,943 ms, elapsed 0.2858 to 0.2864 → 0.2781 to 0.2791 s in the two quiet rounds. Alternating runs, 20 each: median wall 286.0 → 277.3 ms (step 6: 297.9). S unchanged.
Step 10: huge pages for the term table only
A huge page is resident as a whole, so step 7’s allocator cost memory for every large block that only partly fills its last huge page: on the board, 43.1 → 46.3 MB, and still 44.2 MB at step 9. The term table is exactly two huge pages and the pass reads all of it, so it is the one block whose huge pages cost no memory. It is now allocated alone at a 2 MiB boundary and advised once, and the 34-line global allocator goes, with step 8’s trim of the keys, which only mattered on huge pages. Walk cycles: 427 to 517 M with no huge pages, 136 M at step 9, 246 to 257 M now.
Locally, against step 9, three interleaved rounds: cycles 6.87 to 6.90 → 6.85 to 6.90 G, task-clock 2,952 to 2,967 → 2,969 to 2,989 ms, elapsed 0.2755 to 0.2770 → 0.2770 to 0.2791 s. Alternating runs, 14 each, twice: median wall 275.6 and 276.9 → 276.8 and 278.7 ms (no huge pages at all: 282.5 and 282.2). memory.peak over six runs each: 41.3 to 44.9 → 41.2 to 43.8 MB; this machine does not show the board’s difference. S 871 → 849. Gate: 507 pass, 0 fail.
Step 11: no branch on a check’s result
A check adds hit times 1 << SUM_BITS | doc to its cell ([Tally::add_check]), and the
compiler made that product a branch on hit. Whether a document matches a check follows no
pattern, so the branch missed 4.2 M times, 6% of all branch misses. std::hint::select_unpredictable
makes it a conditional move.
Locally, against step 10, three interleaved rounds: branch misses 68.2 → 64.0 M, cycles 6.80 to 6.84 → 6.61 to 6.68 G, task-clock 2,948 to 2,966 → 2,864 to 2,896 ms, instructions 10.06 → 10.22 G. Alternating runs, 16 each, twice: median wall 278.2 and 276.3 → 270.1 and 269.2 ms. S unchanged. Gate: 507 pass, 0 fail.
Step 12: the per-token call inlined
[walk] reported tokens and line ends through one callback that took an enum. The callback held
the whole line-end logic as well, so the compiler kept it out of line and called it once per
token, 36.3 M times on seed 1: each call saved and restored six registers and reloaded the
captured state. walk now takes a token callback and a line-end callback that share a state
argument (the probes), so the token callback, a key, a hash and a prefetch, is inlined into the
loop. The Event enum goes.
Locally, against step 11, three interleaved rounds: instructions 10.22 → 8.86 G, cycles 6.60 to 6.67 → 6.16 to 6.25 G, task-clock 2,858 to 2,893 → 2,669 to 2,710 ms. Alternating runs, 16 each, twice: median wall 272.0 and 270.5 → 255.4 and 254.0 ms (step 6: 297.5 and 295.6). S 849 → 846. Gate: 507 pass, 0 fail.
Step 13: one multiply per token hash
The hash of a token’s key folded its four words with a multiply each, a chain of four dependent
multiplies plus four extractions from the vector register, on every token. It now XORs the words
in the vector register and multiplies once. Equal XORs of different keys only share a probe
sequence, which the head compare still tells apart, and the slots still come from the top
bits of the product.
Locally, against step 12, three interleaved rounds: instructions 8.86 → 8.64 G, cycles 6.18 to 6.19 → 6.01 to 6.04 G, task-clock 2,677 to 2,681 → 2,609 to 2,623 ms. Alternating runs, 16 each, twice: median wall 253.0 and 255.4 → 247.4 and 249.0 ms. S 846 → 844. Gate: 507 pass, 0 fail.
Step 14: the first-match counts in bytes
A check’s first ten matches in a chunk also go to its query’s list of first matches, up to ten per
query, and the query’s own cell counted them. That cell is one of 50,000 u64s per thread, 400 KB,
read at random on 7 M early hits, and mostly from L3. The count now sits in a byte per query
([Tally]), 50 KB per thread, which stays in cache. The query’s cell is no longer touched during
the pass, so it no longer needs zeroing before the checks’ cells are added in.
Locally, against step 13, three interleaved rounds: cycles 6.05 to 6.15 → 5.94 to 6.00 G, task-clock 2,623 to 2,669 → 2,582 to 2,607 ms. Alternating runs, 16 each, twice: median wall 247.9 and 247.3 → 245.4 and 244.8 ms. memory.peak over four runs: 42.2 to 46.2 → 43.7 to 44.6 MB (the bytes add 0.6 MB over 12 threads). S 844 → 845. Gate: 507 pass, 0 fail.
Not kept: each check pushing its first ten matches with no per-query count (format already takes ten per query) gave the same time, 6 M more branch misses, and 4 MB more memory.
Step 15: memory at the peak
Memory peaks when every thread groups its first matches at the end of its chunk: the ungrouped
(query, doc) pairs, about 122,000 per thread on seed 1 (976 KB), coexist with the grouped ids and
the group starts. Two things sat there for nothing. Each thread’s window was still allocated,
its 349 bitset rows (179 KB) included, and [group] cloned its 50,001 group starts (200 KB) as
fill cursors. The window is now dropped after its last flush, and the grouping uses the starts
themselves as cursors, then shifts them back by one place.
Locally, memory.peak over seven runs each: 43.1 to 45.4 MB (median 44.7) → 41.5 to 42.5 MB (median 41.8). The window alone: median 41.9, but one run at 44.9. Cycles and wall unchanged: 5.94 to 5.96 → 5.93 to 5.94 G; alternating runs, 12 each: median 246.0 → 245.1 ms. S 845 → 848. Gate: 507 pass, 0 fail.
Step 16: no zero page under the cells
perf’s kernel profile of step 15 had 9% of kernel cycles in smp_call_function_many_cond,
called from do_wp_page: copy-on-write faults. vec![0; n] takes its cells from calloc, and
calloc leaves fresh pages from mmap unwritten. The pass first touches a page of query or check
cells with the load in *cell += … (load, add, store: the new value is compared next), so the
read fault maps the shared zero page. The store then faults again, and replacing a mapping that
other cores may cache sends an interrupt to every core running the process, to flush its TLB.
On seed 1 that happened for 1,111 pages of query cells and 948 pages of check cells over 12
threads, so 2,059 rounds of interrupts to 11 cores each. [Tally::new] now builds the cells with
[0].repeat(n), which writes them, so each page faults once, on a write.
Locally, against step 15: page faults 18,800 → 16,710, kernel cycles 214 → 156 to 157 M, user cycles unchanged (5.95 to 6.00 → 5.88 to 5.99 G). Alternating runs, 16 each, twice: median 246.4 and 246.1 → 244.9 and 243.4 ms, min 244.2 and 244.5 → 241.5 and 241.4 ms. memory.peak over seven runs: median 41.7 → 41.8 MB. S 848 → 848. Gate: 507 pass, 0 fail.
Not kept: the same writes as black_box(&mut cells).fill(0) after vec!, for the same time
(median 244.6 and 242.9 ms in the same runs) and 5 more lines. Also measured: recording first
matches in chunk 0 only, an upper bound on skipping the other chunks’ first matches once chunk 0
holds ten for a query. Median 244.6 and 245.1 → 248.2 and 248.0 ms: chunk 0 still records and
groups all of its own, so its thread, the one the others wait for, does no less.
Step 17: the corpus pages dropped in parallel
The kernel tears down the process’s mappings in the exit, after the output is written, on one
core. For the corpus mapping that is 61,970 page table entries on seed 1 (254 MB), each a page
cache page whose map count, reference count and cgroup statistics it updates. Each thread now
drops its own chunk’s pages with madvise(MADV_DONTNEED) as soon as its pass ends, so the
twelve cores share that work, mostly while other threads still scan. The range is rounded out to
whole pages: a neighbouring chunk that still reads a shared boundary page faults it back in from
the page cache, with the same bytes, as the mapping is private and never written.
Locally, against step 16, alternating runs, 16 each, three rounds: median 245.3, 242.8 and 243.5 → 241.7, 241.3 and 240.4 ms; min 242.9, 241.6 and 241.1 → 239.7, 236.9 and 238.5 ms. With the range rounded inward instead, to the chunk’s own whole pages: 242.7 → 240.7 ms. Kernel cycles rise a little, 171 to 182 → 178 to 192 M in a noisy session (the same work, spread over cores, plus one TLB-flush interrupt per thread), but no longer at the end. memory.peak over seven interleaved runs: median 41.9 → 42.0 MB. S 848 → 852. Gate: 507 pass, 0 fail.
A second board run of the same code, run-7a898680a856 (from the next push), measured 0.2293 s and 42.2 MB.
Step 18: 12 bytes of the key in each slot
A profile of step 17 by source line (a build with line tables, perf record every 100k user
cycles) put 6.3% of all samples on one line of TermTable::position: the comparison of the
token’s whole key with keys[slot.id], made when the slot’s first 8 bytes match a term longer
than 8 bytes. That load depends on the slot load, so the prefetch made at the token does not
cover it, and keys is 2.4 MB. Far from rare: in the first 25 MB of seed 1, 20% of the tokens
are longer than 8 bytes, and 12.7% of all tokens share their first 8 bytes with a long query
term, nearly all of them (98.5%) 9 to 12 bytes long.
A slot now also holds the term’s bytes 8 to 11 (tail), and the id and the flags share one
u32 (id × 16 + flags), so it is still 16 bytes. LONG marks a term past 12 bytes, and only
those read keys: 0.2% of the tokens. In the same profile that line falls from 3,763 samples
to 38, and all samples from 59,522 to 56,962. Ids from 2^28 up would not fit; TermTable::new
stops with an error before that, at 2^28 term occurrences.
Locally, against step 17: user cycles 5.85 to 5.89 → 5.68 to 5.70 G over five rounds of perf stat -r 5, instructions 8.573 → 8.687 G (the extra compare). Alternating runs (ab.py), 15 or 16
each, five rounds: median 237.3, 237.9, 237.8, 237.2 and 237.1 → 229.8, 229.8, 230.6, 229.5 and
229.5 ms (-3.2%). memory.peak over six interleaved runs: median 43.2 → 43.0 MB (the table is
the same size). S 852 → 857. Gate: 510 pass, 0 fail.
Step 19: 99 fewer lines
K weighs S with an exponent of 0.15 against T’s 0.5, so at B’s numbers one code line is worth about as much as 0.035% of T. This step only cuts lines, except for one alignment.
- Pure restructurings. One
use std::{...}witharch::x86_64::*for the intrinsics (clippy’swildcard_importsallowed in Cargo.toml) replaces nineuselines and the two insideclassifyandprefetch: the machine code is byte-identical. The libc constants sit at their calls, named in comments, exceptMADV_DONTNEED.foldbuildsONESfrom two 32-byte arrays.bool_coverfits its signature on one line through aStepalias. - Cold code.
mainmaps both files through one closure and writes the parts with onetry_for_each.map_filemaps an empty file as one byte past its end instead of a special case.id_atreports a bad line by its byte offset; an emptydocs.txtnow stops with that error, as spec §2.1 has every line end in an LF. The parser looks operators up in a three-entry table.Check::new,Check::unless, the plan’s accessors andQueries::stepseach lose a line or two. - The term table never doubles. It is sized once at 3 slots per 2 term occurrences, plus
one, rounded up to a power of two, so it is at most two thirds full whatever the queries
hold, and a probe always meets an empty slot. On the seeds that is the same 262,144 slots as
before (152,904 occurrences, 75,747 distinct terms on seed 1), so the pass is unchanged. The
rebuild,
placeandhuge_slotsgo intointernandnew. - The walk.
popclears and returns the lowest set bit, and the last partial block is padded once before the loop, so each block isfirst_chunk().unwrap_or(&padded). - The key-mask table on one cache line (+2 lines). A token’s mask is a 32-byte load from
ONESat offset32 - len. The table had byte alignment and sat wherever the other constants left it: at offset 59 of a cache line at steps 17 and 18, where only tokens of 28 bytes or more split the load. These cuts moved it, to offset 11 on step 17’s code, where every token of 10 bytes or fewer split it (split loads 44.3 → 78.4 M, the run 0.7 ms slower), and to offset 43 on step 18’s (tokens of 12 bytes or more, 42.0 → 43.2 M). Aligned, no token splits it, and no later change to the constants can move it.
Locally, against step 18 (alternating runs, 61 each, twice): median 229.8 and 229.7 → 230.1 and
229.9 ms, min 228.3 and 227.9 → 228.8 and 227.8 ms. perf stat: user cycles 5,694 → 5,695 M,
instructions 8,687 → 8,739 M (the walk), split loads 42.0 → 42.2 M. The hot code is the same
apart from the walk and steps; the rest is code placement, which alone moves a run by up to
0.6% here: step 17 with one no-op assert! added to main ran 1.35 ms slower than step 17
itself, and with every function aligned to 64 bytes the cold cuts and step 17 ran the same
cycles. memory.peak over 12 alternating runs: median 43.1 → 42.8 MB. S 857 → 758. Gate: 510
pass, 0 fail.
On the board, run-74f2276732d6 measured 0.2241 s, in a run where track A drew 22.9 ms and track C 38.4 ms, slow draws for both (their usual draws are about 19 and 35 ms).
Step 20: a larger sample, counted in parallel
The plan picks each query’s triggers from how many sampled documents hold each term
([sample_hits]). In the first 1,000 documents most query terms have no hits at all, so they
tie, and the plan picks triggers that the pass then checks more often than it needs to. With
nothing else changed but the constant (the same code layout, on step 17’s code), the pass’s
user cycles on seed 1 were 5.98 G for a 250-document sample, 5.86 G for 500, 5.79 G for 1,000,
5.73 G for 2,000, 5.69 G for 4,000 and 5.66 G for 8,000. Counted on one thread, though, every
1,000 more documents delay the pass by about 5 ms.
The sample is now the corpus’s first 1/64 (SAMPLE_SHARE; 4,005 documents and 4.0 MB on seed
1), split at line starts into one part per thread. Each thread counts its part
([count_hits]), and the parts are summed into the first part’s counts, whose pages are
written already: a new zeroed vector would fault each page twice, once for the first load and
again for the first store. The shares 1/128, 1/96, 1/48 and 1/32 came out within noise of 1/64:
a larger sample costs about as much time before the pass as it saves in it.
Locally, against step 19, alternating runs (ab.py, 14 each), two rounds: median 229.5 and
229.6 → 226.6 and 226.4 ms; the same change written with a loop instead of reduce, in two
other rounds: 229.5 and 230.1 → 226.9 and 227.1 ms. The loop form with every function aligned
to 64 bytes, so that the hot functions, whose code is the same, sit at the same offsets: 230.8
and 230.8 → 226.8 and 226.7 ms. perf stat: user cycles 5.59 → 5.51 to 5.56 G, instructions 8.739 →
8.686 G. In a perf record timeline the pass starts at 21.4 ms instead of 21.1 to 22.0 ms, and
its threads’ cycles fall 5.59 → 5.51 G. memory.peak over six interleaved runs: median 41.2 →
41.0 MB. S 758 → 771. Gate: 510 pass, 0 fail.
Step 21: 35 fewer lines, loops on 64-byte boundaries
Cuts in code that runs once per run or once per thread:
- One
parallelhelper (7 lines) runswork(i)for eachion a thread of its own and returns the results in order. The pass, the output and the query parse each spelled out athread::scopein 8 to 12 lines; each now takes 2 to 4 (-15 in all). The sample keeps its own: it adds each part as its thread is joined, and collecting every part first made the sample 0.08 to 0.19 ms longer (min and median of 15 timed runs). - The intern loop without its prefetch 16 terms ahead (-5). The serial end of the parse (table allocation, merge and intern of seed 1’s 152,904 term occurrences) took 5.49 ms with it and 5.48 ms without, median of 15 timed runs each.
- The output adds a query’s cells over all chunks and splits the total once (-2): together
the chunks’ id sums stay below
2^SUM_BITS, as each one does, sinceanswer_allbounds the sum of all ids. The first matches come straight from the chunks throughflat_map(..).take(SHOWN_IDS)instead of a buffer, andChunk’s fields areatandids, so its literal fits on one line (-8). Plan::newnumbers a stored term’s bitset row or id list from one two-entry counter (-4), andline_boundstakes its last bound from the loop: a cut atdocs.len()finds no LF after it (-1).
Loops on 64-byte boundaries. Built as before, this step ran slower than step 20 though it
adds no work: alternating runs (ab.py, 61 each), two rounds, median 226.4 and 226.2 → 227.2
and 227.0 ms. Each cut alone on step 20, two rounds: the helper +0.41 and +0.38 ms, the intern
loop +0.07 and -0.13 ms, the rest +0.88 and +0.85 ms. The cost is where the hot loops sit. The
Plan::new cut alone, which runs once and leaves the instruction count at 8,686.1 M, moved the
scan thread’s code, byte for byte the same, from offset 16 of a 64-byte line to offset 0, and
user cycles rose 0.3 to 0.6%. -C llvm-args=-align-loops=64 in .cargo/config.toml starts every
loop on a 64-byte boundary; executing the padding adds 28 M instructions (8,683 → 8,711 M).
Step 20 built that way ran 226.5 and 226.3 ms, this step 225.9 and 225.8 ms, in the same
sessions as step 20 as built before at 226.0 and 226.0 ms. A loop now keeps its offset in a
line wherever later changes move its function.
Locally, against step 20 (alternating runs, 41 and 61 each): median 226.00 and 225.99 → 225.86 and 225.80 ms, min 224.90 and 225.00 → 224.32 and 224.15 ms. memory.peak over 10 and 16 alternating runs: medians 42.95 and 42.74 → 43.61 and 42.93 MB. S 771 → 736. Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their reference hashes.
Step 22: 8 fewer lines, the same machine code
Four spots in code that runs once, written so that rustfmt keeps them on fewer lines:
- In
answer_all, the chain that reads each chunk’s first id and the check on the document count each put their receiver in parentheses, so each is a one-call chain that fits on one line (-5). bit_index_sumnames its per-mask closure,weight(-1).TermTable::newbinds the emptykeysfirst, so the struct literal fits on one line (-2).
Checks: the built binary’s .text and .rodata are byte for byte those of step 21, and only
88 bytes of .data.rel.ro differ (the line numbers in panic locations), so T and memory are
unchanged. S 736 → 728. Gate: 510 pass, 0 fail.
Step 23: a check’s terms in one gather
On seed 1 the per-document checks ([Check]) run 16.9 million times. Each one built its truth
table’s index from its six terms: per term a bounds-checked load of the document’s bit set
seen, a shift and an OR. With the loads unchecked, that still took 29 cycles a check:
0.49 G of 5.49 G user cycles on step 20.
Now one AVX2 gather (vpgatherdd) loads the 32-bit words of seen that hold the six terms’
bits, a variable shift moves each bit to the top of its lane, and movemask collects the six
bits as the index. The two spare lanes read word 0 and are masked off. Every term id, and the
pad miss, is below 64 * seen.len(), so no lane reads outside seen; the loop that clears
the document’s bits at its end skips its bounds check on the same grounds. Gather Data
Sampling, whose mitigation slows gathers, does not affect Raptor Lake (locally the kernel
reports “Not affected”).
Locally, against step 21, whose .text and .rodata step 22 keeps (alternating runs, ab.py,
20 each), two rounds: median 226.44 and 225.92 → 215.61 and 215.19 ms, min 224.58 and 224.32 →
214.20 and 213.85 ms. perf stat: user cycles 5.64 → 5.30 to 5.31 G, instructions 8,711 → 7,517
M; branch misses 57.3 → 58.7 M. On step 20, built with every function aligned to 64 bytes, the
unchecked loads alone ran 226.6 → 221.1 ms and the gather on top of them 213.8 ms.
memory.peak over six alternating runs: median 43.5 → 43.2 MB. S 728 → 732. Gate: 510 pass, 0
fail; seeds 2, 3, 7, 10 and 12 match their reference hashes.
Step 24: one loop over a document’s checks
A document kept the check range of each BOOL trigger it held, and at its end ran a loop over
each range. On seed 1 the 8.56 million ranges hold 1 check (4.0 M), 2 (2.28 M), 3 (1.17 M), 4
(0.57 M) or more (0.37 M), with no pattern from one to the next, so the exit of nearly every
range’s loop mispredicted. Profiled with the last branch record (perf record -b, the
mispredicted entries counted by branch address), that exit drew 13% of step 23’s
mispredictions, after the term table probe’s compare (25%), the stored-term test (22%) and the
first-sighting test (16%).
The trigger now appends its check indices to one list for the document: four written at once and the list cut back to the range’s length, so no branch depends on that length, plus a loop over the indices past four, which runs for one trigger in 23. At the document’s end one loop runs the whole list.
Locally, against step 23 (alternating runs, ab.py, 20 each), three rounds: median 216.91,
217.53 and 215.92 → 212.68, 211.64 and 211.56 ms, min 215.02, 214.46 and 214.59 → 210.38,
210.73 and 210.50 ms. perf stat: branch misses 58.5 → 52.0 M, user cycles 5.32 → 5.23 G,
instructions 7,517 → 7,625 M. memory.peak over six alternating runs: median 43.8 → 43.3 MB.
S 732 → 733. Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their reference hashes.
Step 25: a token loop without branches on what a token is
Step 24’s 52 million mispredicted branches came from four tests per token, counted by branch
address in the last branch record (perf record -b): the term table probe’s compare (34%),
whether the doc held the term already (20%), whether the term is stored (26%) and whether it
triggers BOOL checks (11%). Each tests a property that follows no pattern from one token to
the next. On seed 1, 79% of the 36.3 million tokens are query terms, 78% of those are new in
their document, and of the new ones 53% are stored and 38% are triggers.
- Id 0 is no term. The table’s first key is a placeholder, so term ids start at 1, and an
empty slot, all zero, carries id 0 and no flags. A probe for a token that is no query term
returns that empty slot, and the pass treats the token as any other: bit 0 of
seen, id 0 in the doc’s terms, nothing stored or triggered. A token pastMAX_TERMbytes takes a key of 0xFF bytes, which no term has. The sample counts its misses at id 0, which no query reads. - One branch per probe. The compare uses
^,|and&instead of&&, and the test that ends the probe (an empty slot, or the term) goes throughblack_box: as one value it stays one branch, mostly taken, where LLVM split it into two, the first of which mispredicted on every token that is no query term. - Lists by store and add. A conditional move picks the term’s flags when the doc did not hold it yet, and 0 when it did. The term id is written at the end of the doc’s stored-term list and at the end of its trigger list, and each list’s length grows by the matching flag bit, 0 or 1. Both lists have one entry per token, so neither needs a capacity test. After the doc’s last token, one loop does the stored adds and one appends the triggers’ checks, as before.
Built up step by step on step 24, median of 14 to 18 alternating runs: the empty slot as the
probe’s result for misses, with the compare’s two branches as LLVM left them, 211.9 → 209.7 ms; the lists by
store and add on top, 195.0 ms; one branch per probe, 189.6 ms; id 0 for the empty slot
instead of an id written into every empty slot after planning, 187.0 ms; the conditional move
and the ^ compare instead of & between booleans, 183.6 ms. Two versions lost. The single
probe branch alone, with the old tests after it, ran 216.8 ms against 209.7: each token’s
randomness moved into the first-sighting test. Doing the stored add and the check append for
every token, the spare row and list absorbing the others, cut mispredictions to 24 M but
added 2.8 G instructions: 5.76 G user cycles against 5.18 G.
Locally, against step 24 (alternating runs, ab.py, 18 each), two clean rounds: median 212.38
and 211.81 → 183.60 and 183.71 ms, min 210.92 and 210.03 → 182.48 and 183.17 ms. Two other
rounds, run while the box was loaded (load average 7 to 8), are left out. perf stat: branch
misses 52.1 → 20.8 M, instructions 7,625 → 8,392 M, user cycles 5.23 → 4.42 to 4.44 G.
memory.peak over six alternating runs: median 42.6 → 42.9 MB. S 733 → 738. Gate: 510 pass, 0
fail; seeds 2, 3, 7, 10 and 12 match their reference hashes.
Step 26: stores to clear a document’s bits, and the probe’s test in a register
- Clearing by stores. After a document’s last token, a loop cleared each token’s bit in
seenwith a load, an AND and a store. Tokens whose bits share a word, among them every token that is no query term (bit 0 of word 0), made a chain through memory, each load waiting on the store before it. Every set bit belongs to one of the document’s terms, so setting each term’s word to 0 clears them all, with a store and no load. - The probe’s test in a register.
black_box, which kept the probe’s end test one branch in step 25, writes its value to the stack and reads it back, which adds a store-to-load forward to every probe. An emptyasm!block that takes the value in a register hides it from LLVM the same way, with no memory access.
Each alone, against step 25 (median of 18 alternating runs): the stores 3.5 ms, the asm block
1.7 ms. Locally, against step 25 (alternating runs, ab.py, 18 each), two rounds: median
183.40 and 183.54 → 179.01 and 178.44 ms, min 181.87 and 182.22 → 177.50 and 177.52 ms.
perf stat: user cycles 4.39 to 4.44 → 4.31 G, instructions 8,392 → 8,236 M, branch misses 20.8
→ 20.9 M. memory.peak over six alternating runs: median 42.7 → 43.6 MB. S 738 → 740. Gate:
510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their reference hashes.
Step 27: the queries planned on every thread
On seed 1 the pass started about 21 ms into the run, and one thread spent 4.9 ms of that in the per-query planning loop: for each of the 50,000 queries, the phrase’s trigger term or the BOOL query’s cover, its checks, or its stored terms.
- The plan in parallel. Every thread now plans a share of the queries, as the parse does,
and returns its (trigger term, phrase) and (trigger term, check) pairs and its queries on
sets, each in query order.
groupreads the parts in order, so each term’s phrases and checks come out in the same order as before. A term’s PHRASE and BOOL flags follow from the groups (its group is not empty), and one thread still numbers the stored terms in query order, from the queries on sets. - No test for empty slots. The flags were added to the term table slot by slot, behind a test for an empty slot, which mispredicts often, as empty slots lie at random. An empty slot holds id 0, whose flags are 0, so every slot now takes the add, without the test.
Timeline over three instrumented runs: the loop 4.9 → 1.0 to 1.1 ms, adding the flags 1.5 → 0.5 to 0.7
ms, and the pass starts at 16.7 to 17.2 ms instead of 20.7 to 21.7. Locally, against step 26
(alternating runs, ab.py, 18 each), two rounds: median 178.38 and 178.94 → 174.46 and 174.79
ms, min 177.18 and 177.43 → 173.36 and 173.27 ms. perf stat: user cycles 4.30 to 4.31 → 4.31 G,
instructions 8,236 → 8,254 M. memory.peak over ten alternating runs: median 42.5 → 42.0 MB.
S 740 → 744. Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their reference hashes.
Step 28: the sample and the intern without stalls
Three cuts to the work that runs before the pass:
- The sample probes as the pass does. Each sampling thread looked a token up as soon as it
found it, so each probe’s slot load stalled in turn, and branched on whether the document
had counted the term yet. It now collects a line’s tokens with a prefetch of each one’s home
slot, probes them at the line end, as [
scan] does, and addscounted != doc, 0 or 1. - An intern with no branch on a new term. Half of the 152,904 term occurrences are new terms, at random. The slot is now written either way, with its id or the next one, picked by a conditional move, and the key is pushed, then cut off again unless the term is new.
- One line end for the sample. The sample’s end came from
line_bounds(docs, 64), which reads around all 64 cuts, faulting in their pages, to use one.line_endfinds that one.
Timeline over three instrumented runs: the intern 4.7 to 5.0 → 3.9 to 4.3 ms, the sample’s end 0.3 →
0.05 ms, the sample 4.8 to 5.1 → 3.4 to 4.0 ms (a third run of step 27, slowed by other load, took
6.5). Locally, against step 27 (alternating runs, ab.py, 20 each), three rounds: median
174.96, 175.52 and 175.31 → 173.39, 173.52 and 173.54 ms, min 174.24, 173.97 and 172.99 →
172.68, 172.50 and 171.83 ms. perf stat: user cycles 4.32 to 4.34 → 4.34 to 4.36 G, instructions
8,254 → 8,263 M, branch misses 20.8 → 20.5 M. memory.peak over eight alternating runs: median
43.0 → 42.4 MB. S 744 → 746. Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their
reference hashes.
One probe helper shared by the sample and the pass, a line shorter, changed how the pass’s loop was compiled and ran 183.8 ms against 175.0 for step 27, so the pass keeps its closure.
Step 29: the sets path
On seed 1, 1,773 queries run on sets, over 350 bitset rows and 2,787 id lists. Each thread flushes a window every 4,096 documents, and the pass adds 9.9 million row bits and 1.9 million list entries.
- One sum per query and window. The flush handed each of a query’s 64 result words to
add_word, which loaded and stored the query’s cell each time, so the 64 calls formed a chain through memory.add_bitsnow records the first matches one by one while the query lacks them, as before, and then counts the whole window in one sum over its words, which the compiler vectorizes: per word a popcount, and the id sum as before ([bit_index_sum]). - A
u32store code. A term’s [Store] was an 8-byte enum; it is now au32,kfor bitset rowkandLIST | jfor id listj, which halves the per-term array the pass reads for every kept term, and takes 6 lines fewer. - Rows and lists listed apart. The branch on whether a kept term is a row or a list drew a fifth of the remaining mispredictions (last branch record, by address), as the two kinds follow no pattern. A slot now carries two flags, ROW and LISTED, in place of STORED, and the token loop lists each kind apart by a store and an add, so each loop of adds has one kind. The term id moves up a bit, so the table takes up to 2^27 term occurrences.
Built up on step 28 (median of 18 to 20 alternating runs, rounds against the same step 28
binary): the u32 code 173.74 → 172.14 ms; the sum per window on top 172.05 → 168.78; the
lists apart on top of that 169.72 → 168.34. Locally, against step 28 (alternating runs,
ab.py, 18 to 20 each, with other jobs on the box, load average 4 to 7), three rounds: median
173.14, 174.52 and 174.12 → 168.32, 168.92 and 169.58 ms, min 171.99, 172.55 and 172.64 →
167.31, 167.11 and 167.60 ms. perf stat: user cycles 4.30 to 4.31 → 4.15 G, instructions 8,263
→ 8,261 M (the sum saves about 310 M, the second list adds as many), branch misses 20.5 →
18.3 to 18.4 M. memory.peak over eight alternating runs: median 41.3 → 40.8 MB. S 746 → 745.
Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their reference hashes.
Comparing a phrase’s span term by term instead of as slices, which calls bcmp, gained
nothing: median 171.91 ms against 171.52 ms, 18 alternating runs each.
A second run of the step 29 code, run-2d06517dbcd4, measured 160.2 ms and 42.2 MB (73.8 points).
Step 30: a plain static executable
.cargo/config.toml adds -C target-feature=+crt-static and -C relocation-model=static, so the
binary is a plain static executable at a fixed address, with no dynamic loader and no
position-independent code. In track A the same change ran 3.9% fewer cycles, with half the iTLB
misses; here the gain is smaller. A static PIE alone measured nothing at step 14 (experiments
below).
Local, turbo off: ab.py against step 29, 16 interleaved runs, five rounds: medians 168.49 →
168.05, 169.05 → 168.17, 169.66 → 168.04, 168.57 → 167.54 and 168.25 → 168.58 ms, minimums
167.37 → 165.93, 167.15 → 166.76, 167.45 → 166.86, 167.84 → 166.44 and 167.50 → 166.34 ms.
S unchanged at 745. Gate: 510 pass, 0 fail.
Step 31: the token loop’s stores without bounds checks
After step 29 the token loop ran about 100 instructions per token. It is a closure, and the
four per-token vectors it wrote (the term ids, and the rows, lists and BOOL triggers kept) were
captured Vecs: LLVM cannot tell that a store into one of their buffers leaves the Vec
headers alone, so after every store it reloaded each header’s pointer and length from memory,
and checked each index against the length. With the loop’s registers taken, more spilled.
- One slice, four runs. The four vectors are one now, sliced to
4 * nentries for a document ofntokens: the term ids from 0, then the rows, lists and BOOL triggers kept fromn,2nand3n, each up to its cursor. The slice’s pointer stays in a register, and the writes take no bounds check: a cursor moves at most once per token, so it stays in its run. - The seen word unchecked. A token’s word of
seenis read and written without a bounds check, as the clearing loop already did (step 23); anassert!whereseenis sized states the bound. - The probes read in place. The loop reads each (key, home slot) from the probe list
instead of moving it out with
drain, which copied the 32-byte key to the stack.
Built up on step 29 (local, 18 to 20 alternating runs, rounds against the same step 29
binary): the three kept vectors unchecked 168.95 → 165.97 ms; with the seen word and a fourth
vector for the term ids, 169.08 → 163.80; the four as one slice 169.08 → 158.80 (the same
round); the probes read in place on top of that, 160.05 → 158.60 and 159.58 → 157.92 ms.
Locally, against step 30 (ab.py, 20 alternating runs each, with other jobs on the box, load
average 7 to 11), three rounds: median 169.99, 172.52 and 169.26 → 158.49, 159.94 and 158.42 ms,
min 167.46, 166.78 and 167.99 → 156.55, 157.30 and 156.29 ms. perf stat: user cycles 4.01 →
3.62 G, instructions 8,268 → 7,338 M, branch misses 18.2 → 18.1 M. memory.peak over eight
alternating runs: median 41.3 → 40.9 MB. S 745 → 746. Gate: 510 pass, 0 fail; seeds 2, 3, 7,
10 and 12 match their reference hashes.
Taking seen as a slice inside the closure cut 81 M more instructions but did not measure. A
flag in the term table marking a home slot that a term was displaced from, so that a probe
ends at its home slot unless the flag is set, sent 1.39 million of the 36.8 million lookups
past the home slot and cut branch misses from 18.4 to 15.6 M, but it added 91 M instructions,
the user cycles stayed at 4.13 to 4.16 G, and the wall did not move: 169.69 → 169.10 and 168.87
→ 169.29 ms, for 9 more lines. Without #[inline(always)], its lookup was no longer inlined
and the run took 11 ms longer.
Step 32: the sources mounted, not copied
The Dockerfile’s build stage mounts its context (RUN --mount=type=bind,target=/src) instead of
copying it with COPY . ., and cargo builds into --target-dir /out, since the mount is
read-only. harness/dockerfile_check.py accepts a bind mount of the context, and the board
built track A’s Dockerfile with the same mount (its step 45). A local docker build --network=none gives a binary byte-identical to step 31’s, so T and M cannot move. S 746 →
745.
Step 33: the first matches without a branch on a check’s result
After step 31, Tally::add_check still took a branch on each check’s result: step 11 made the
add to the cell a conditional move, but recording a first match (hit, the check’s count at most
SHOWN_IDS, and its query’s count below SHOWN_IDS) branched on hit first. A check’s result
follows no pattern and comes at the end of a chain of loads, the check’s terms and then the
gather of their words of seen, so the branch resolved late and often missed.
[Tally::add_checks] now takes all of a document’s triggered checks. For each, it adds to the
cell with a conditional move as before, writes the check’s query at a cursor over the front of
the list of checks, and moves the cursor on when the check matched and is within its first
SHOWN_IDS matches, so no branch depends on the result. A second loop then records the first
matches from the queries before the cursor: 678 K of the 16.9 M checks evaluated reach it, and
502 K are recorded. It is a method so that LLVM knows the stores to the cells and to the list
leave self alone, and keeps the addresses of its vectors in registers.
Local, against step 31 (ab.py, 20 alternating runs, load average 2 to 6), four rounds: medians
156.66, 157.64, 157.21 and 156.48 → 152.23, 152.33, 153.10 and 152.11 ms, minimums 155.37,
155.21, 155.82 and 155.02 → 151.04, 151.06, 150.88 and 150.80 ms. perf stat: user cycles 3.82
→ 3.69 G, instructions 7,338 → 7,257 M, branch misses 18.1 → 16.9 M. memory.peak over five
alternating runs: median 41.3 → 41.3 MB. S 745 → 750. Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10
and 12 match their reference hashes.
Moving the loop into the method alone, with the branch on hit kept, cut instructions to
7,202 to 7,270 M but left branch misses at 18.1 M and user cycles at 3.79 to 3.82 G, inlined or not.
Writing every check’s (query, document) into the spare capacity of the first-match list and
adding to its length only for a first match cut branch misses to 16.3 M but added 121 M
instructions, for 3.81 G cycles. A single compare of the cell against a limit that is 0 on a
miss became two branches again, with 22.9 M misses and 4.03 G cycles; held in a register by an
empty asm! block, it stayed one compare, but the misses stayed at 18.1 M.
Step 34: the term lookups without bounds checks
After step 33 each token’s lookup still checked bounds: [TermTable::position] checked each
slot it probed, find_from checked the index that position returned, and prefetch took a
reference, which cost a check to make, for each token’s home slot and each BOOL trigger’s
checks and cells. The token loop also reached the term table and seen through the closure’s
captured references, so it reloaded their addresses after its stores.
- The probe unchecked.
positionandfind_fromareunsafe fns that take a slot index, as [TermTable::home] gives one: it shifts the hash down to the slot count’s bits, and the probe wraps at the count. The table has 2 slots or more, so that the shift stays below 64. - Prefetches by pointer.
prefetchtakes a raw pointer, made withwrapping_add: a prefetch of any address is harmless. - The table and
seenas locals. The token loop takesplan.termsand a slice ofseenonce per document. Step 31 found the slice alone did not measure, for 81 M fewer instructions; with the table, it cut 99 M.
Built up on step 33 (perf stat): the prefetches by pointer, instructions 7,257 → 7,220 M; the
probe unchecked as well, 7,079 M, user cycles 3.69 → 3.66 G; the table and seen as locals,
6,980 M and 3.56 to 3.64 G. Branch misses stayed at 16.8 to 16.9 M. ab.py, 18 alternating runs, two
rounds, step 33 / the probe unchecked / all three: medians 152.84 / 151.19 / 150.65 and 152.63 /
150.84 / 150.26 ms, minimums 150.77 / 149.93 / 149.18 and 151.52 / 149.94 / 149.35 ms.
Local, against step 33 (ab.py, 20 alternating runs, load average 3 to 5), three rounds: medians
153.42, 153.74 and 152.45 → 151.11, 151.83 and 151.14 ms, minimums 151.91, 152.08 and 151.64 →
149.87, 148.39 and 149.27 ms. perf stat: user cycles 3.69 → 3.56 to 3.65 G, instructions 7,257 →
6,980 M, branch misses 16.9 → 16.8 M. memory.peak over five alternating runs: median 41.9 → 41.6
MB. S 750 → 751. Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their reference hashes.
Splitting the token loop in two, all of a document’s lookups first and then the rest from their flags, added 185 M instructions and 0.4 M branch misses, for 3.65 G cycles against 3.64 G. A term table of 4-slot buckets, one 64-byte line each, with a key’s home slot at the start of a bucket and the key compared with all four slots in two AVX2 compares, kept the linear probe only for long keys and for misses in a bucket whose last slot is taken, 0.9% of lookups: branch misses 16.9 → 12.4 M, but instructions 7,257 → 7,697 M and user cycles 3.70 → 3.85 G.
The board’s run of this step, run-401b90111691, drew 161.8 ms, against 145.5 ms for step 33’s: a slow draw. In the same run, track C’s unchanged code drew 48.4 ms, against its usual 29 to 31 ms.
Step 35: fewer instructions in the corpus pass
After step 34 the pass ran 6,980 M instructions on seed 1, about 189 per token, at close to the core’s limit of instructions per cycle, with no single hot spot: the probe took about 16% of the cycles, the key and its hash 10%, the checks 9%, the BOOL triggers 6%, and the rest was spread over the tokenizer, the seen bits, the rows and lists, and the phrases. So this step cuts instructions wherever the machine code showed reloads, bounds checks or tests it did not need.
- The checks unchecked. [
Tally::add_checks] is anunsafe fnwhose indices are a document’s checks, so it reads each check and its cell, and writes the first-match queries, without the three bounds checks that took 6 of its 33 instructions per check. - The triggered checks in a slice sized once. Each term triggers once per document and no
two terms share a check, so a document has at most all the checks: their indices go into a
slice of that length plus 4, allocated once per thread, at a cursor, instead of a
Vecthat tested its capacity and was truncated once per trigger. The term’s range of checks is read from a local slice ofcheck_at, whose address stays in a register; so are the slices of the stores and rows that the rows and lists loops index. - The carried token picked once per block. A token still open at a block’s end closes at
the next block’s first end. [
walk] picked its start with a conditional move at every end; it now picks the start that the block’s first end closes once per block, by a conditional move, and each end takes the next start with no test. - A key in fewer steps.
key_intakes the token’s 32-byte window with one bounds check instead of two, andkey_hashfolds two words instead of four. A key of 16 bytes or less hashes as before, since its last two words are zero, so their slots do not move. - Phrases compared inline. A phrase’s terms are compared with the document’s in a loop
that ORs their differences, instead of a call to
memcmpper candidate, which also reloaded three registers after each call. - The long-key test in the tail. No letter or digit has the top bit of a byte, so a slot’s
tailkeeps in its top bit whether the term runs past 12 bytes, and the probe’s compare ofheadandtailcovers it: theLONGflag and its test at each probe step are gone.
Measured on battery with the power-saver profile (EPP power), so no wall times: perf stat
counts only, battery, not comparable with the steps before. Built up on step 34, instructions:
the long-key mark in the tail 6,980 → 6,962 M; add_checks unchecked 6,823 M; the local slices
for the rows and lists 6,826 M, with user cycles 24 to 54 M lower in two rounds; phrases inline
6,751 M, with branch misses 17.0 → 17.6 M; the checks in a sized slice 6,556 M, branch misses
16.6 M; the window with one bounds check 6,444 M; the two-word hash 6,370 M; the carried token
picked once per block 6,179 M.
Against step 34 (perf stat -r 3, three alternating rounds; battery, not comparable): user
cycles 3,661 to 3,672 → 3,361 to 3,391 M, instructions 6,980 → 6,178 M, branch misses 16.9 → 16.6 M.
memory.peak over five alternating runs: median 42.2 → 41.5 MB. S 751 → 761. Gate: 510 pass, 0
fail; seeds 2, 3, 7, 10 and 12 match their reference hashes. The board’s run,
run-8bf61f0fec95, measured 131.3 ms and 43.3 MB, against 145.5 ms and 41.3 MB for step 33’s.
On AC power again (profile performance, turbo off), ab.py, 20 alternating runs, two rounds:
medians 151.75 and 150.43 → 140.81 and 140.10 ms, minimums 149.67 and 148.58 → 139.43 and
139.21 ms, 6.9 to 7.2% faster.
Peeling the carried token out of the loop behind a branch cut instructions to 6,259 M but added
0.6 M branch misses, as whether a block starts inside a token follows no pattern; peeling only
the block’s first end, with the conditional move kept there, cut them to 6,332 M. Writing the
rest of a range of more than four checks through a zip added 120 M instructions; writing it
at an offset from the cursor, one line shorter, added 8.5 M and 0.1 M branch misses.
Step 36: a shorter serial start
After step 35 the pass started 14.2 to 14.9 ms into a run on seed 1 (local, on AC, turbo off, a build with timestamps, 12 threads on the P-cores, medians over three rounds of 11 or more runs). Interning the query terms on one thread took 3.7 ms, the sample 3.4 to 3.7 ms and the planning 1.3 ms, all of it before the pass.
- The intern prefetch put back. [
TermTable::intern] takes the parsed keys and an index, and starts loading the home slot of the key 16 places on, so that its probe seldom waits: interning 3.60 → 3.02 ms. After step 33 it saved about 0.35 ms for 3 more lines and was left out; it now takes 2. - Lengths instead of keys. The table kept each term’s 32-byte key, pushed at each occurrence and dropped again unless the term was new: 2.4 MB for seed 1’s 75,747 terms. The costs read only the keys’ lengths, and the probe only the keys longer than 12 bytes, which a slot does not hold whole (13 terms on seed 1). The table now keeps each term’s length in a byte, and the long keys in an array of zeroed entries, one per term occurrence and one for id 0: only a new long term writes its key at its id, and every other key is written to entry 0, which no probe reads, so that no branch is taken. On seed 1 its written entries take one 2 MiB huge page. Interning without the prefetch: 3.73 → 3.60 ms.
- Costs where the planning reads them. A term’s cost is computed from its sample hits and its length when a query is planned, instead of read from a table that one pass over the hits and the keys filled first: the planning 1.30 to 1.34 → 0.98 to 1.06 ms.
- The sample in one cell per term. [
count_hits] kept, per term, a count and the last document counted in two arrays, so each token cost two random accesses, and the second array, 606 KB per thread, took 148 page faults on each. Au32cell now holds the count in its high half and the last document’s number in its low half: the sample 3.40 to 3.72 → 2.33 to 2.46 ms. - The flags in bytes. The flags that [
TermTable::mark] adds to the slots are collected in bytes instead ofu32s: 0.15 to 0.16 → 0.04 ms.
In the round that timed both, the pass started at 14.24 ms for step 35 and 12.06 ms for this step; over three rounds each, at 14.24 to 14.86 and 12.06 to 12.50 ms, and the pass itself took 118.8 to 121.6 and 119.5 to 119.8 ms.
Local, against step 35 (ab.py, 20 alternating runs on the P-cores, on AC), two rounds: medians
139.93 and 140.59 → 137.99 and 138.03 ms, minimums 138.94 and 138.95 → 135.71 and 136.54 ms.
perf stat on CPUs 12-15: instructions 6,080 → 6,090 M, page faults 11,949 → 10,560; on the
P-cores, page faults 19,235 → 16,669. memory.peak over 12 alternating runs on the P-cores:
median 42.3 → 41.4 MB. S 761 → 761. Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their
reference hashes.
The grouping’s arrays written when allocated, as tried after step 17, took the checks’ grouping from 1.27 to 1.32 ms, with 10,564 page faults against 10,560. The prefetch 8 or 32 places on: interning 3.17 and 3.15 ms, against 3.09 at 16. The table’s flags added on every thread, a share of the slots each: marking and the rest of the plan 0.83 → 0.69 ms, for 3 more lines. On battery, the plan’s groups placed on every thread, a range of keys each, took the phrases’ grouping from 0.47 to 1.33 ms and the checks’ from 2.03 to 1.65 ms, and the start from 20.51 to 21.53 ms; the sample’s counts summed on every thread after a barrier took the start from 19.13 to 18.92 ms, for 15 more lines. A long key found by a binary search in a sorted list of the long terms, or in a cold function, instead of in an array by id, added 200 to 302 M instructions to the pass, as the probe loop then spilled registers.
The board’s run, run-ce4c2e1d13c6, drew 134.2 ms against 131.3 ms for step 35’s, on a slow box: in the same run, track C’s unchanged code drew 60.1 ms, against its usual 27 ms. A second run of the same commit, run-fa751616d535, drew 169.1 ms and 39.9 MB, while track C’s unchanged code drew its usual 27.2 ms in it, so this draw was slow for B alone. A third, run-ab34f37502a1, drew 131.2 ms and 42.6 MB.
Step 37: the term table’s huge pages asked for again
On the board, B’s wall time follows its memory.peak. Step 36 drew 134.2 ms at 42.8 MB, 169.1 ms at 39.9 MB and 131.2 ms at 42.6 MB, and step 34 drew 161.8 ms at 40.5 MB, the lowest memory of steps 30 to 36. A run whose blocks get no transparent huge pages takes less memory, as nothing is rounded up to 2 MiB, and its random reads into the term table walk the page tables.
Locally, step 36 run with THP off for the process (prctl(PR_SET_THP_DISABLE), which execve
keeps), on the P-cores, medians of four runs with and four without: cycles 3,514 → 3,726 M
(+6.0%), instructions 6,336 → 6,339 M, dTLB load misses 2.5 → 22.3 M, page faults 16,644 →
17,664, memory.peak 41.5 → 39.1 MB. Sampled without THP (mem_inst_retired.stlb_miss_loads),
58% of the loads that miss the STLB are the prefetches of each token’s home slot, and 22% the
BOOL triggers’ prefetches of their checks and cells. With THP, 2.0 M remain, 45% of them at the
checks’ prefetch: the checks take 1.6 MB, too little for a huge page.
- The collapse. Once the table is written,
madvise(MADV_COLLAPSE)(Linux 6.1 on) collapses its 4 KiB pages into huge pages if its faults found no free one, synchronously, with direct compaction if needed, whatever the sysfs THP settings say (madvise(2)). Where the faults got huge pages, the call returned in 33 to 172 µs in three runs. With THP off while the table is written and back on before the call, the collapse took 1.38 to 1.48 ms and gave back the counts with THP: cycles 3,521 M, dTLB load misses 2.50 M, memory.peak 41.1 MB. With THP off for the whole process, it fails and changes nothing: cycles 3,736 M.
In 12 alternating runs each, neither step 36 nor this step lost the table’s huge pages on this
machine, although 5% of its THP faults since boot fell back to 4 KiB pages and 91% of its direct
compactions failed (/proc/vmstat). So the collapse helps where the faults could not, or did
not try to, compact memory, and costs a fraction of a millisecond elsewhere.
Local, against step 36 (ab.py, 20 alternating runs on the P-cores, on AC, load average 4 to 6),
six rounds: medians 139.16, 137.95, 137.61, 138.70, 138.55 and 137.73 → 138.67, 138.71, 138.53,
138.27, 138.88 and 137.75 ms, minimums 136.68, 136.40, 136.31, 136.48, 137.41 and 136.07 →
136.86, 136.79, 137.34, 136.68, 137.12 and 136.98 ms: no change beyond the noise. memory.peak
over 8 alternating runs: median 42.2 → 41.1 MB. S 761 → 762. Gate: 510 pass, 0 fail; seeds 2, 3,
7, 10 and 12 match their reference hashes.
A table of half the slots, 131,072, at most 58% full, took the dTLB load misses without THP from
22.3 to 13.7 M, but its longer probes took 4.3% more instructions: cycles 3,726 → 4,175 M
without THP and 3,514 → 3,983 M with it. Prefaulting the table with MADV_POPULATE_WRITE
instead of the stores goes through the same faults, so it gets huge pages no more often. Not
built: a second, small table for the commonest terms, probed first. In the first 16 MB of seed
1, the 4,096 commonest query terms are 64% of the tokens, so those probes would stay on a few
dozen pages, but every other token would probe both tables.
Step 38: no frees after the output, and its numbers without write!
After the pass, a run of step 36 spent 3.6 ms more (local, on AC, a build with timestamps, the
P-cores, medians of 8 runs): formatting took 1.83 ms on every thread, the frees when
answer_all returned 1.14 ms, and writing the file 0.63 ms. Step 37 changes nothing there.
-
No frees after formatting. The plan and the chunks are
ManuallyDrop, soanswer_allno longer unmaps their blocks before it returns: the process exits once the output is written ([main]), which already left the output itself unfreed. The frees: 1.14 → 0.06 ms, for the queries, still dropped. After step 33 the same leak, plan, chunks and queries, measured -0.96, +0.10 and -1.80 ms in three rounds of 20 runs, too noisy to keep it. -
Numbers by
format_into.format_into, with aNumBuffer, writes a number’s digits without the formatting machinery ofwrite!. Each number goes out followed by a space, and the line’s last space becomes its LF: formatting 1.83 → 1.44 ms.
In the timing build, a run took 135.65 → 134.14 ms (median of 8).
Local, against step 37 (ab.py, 20 alternating runs on the P-cores, on AC, load average 4 to 6),
four rounds: medians 138.53, 138.27, 138.88 and 137.75 → 137.86, 138.38, 139.08 and 137.15 ms,
minimums 137.34, 136.68, 137.12 and 136.98 → 135.85, 136.61, 137.15 and 136.31 ms. memory.peak
over 8 alternating runs: median 41.1 → 41.1 MB. S 762 → 763. Gate: 510 pass, 0 fail; seeds 2, 3,
7, 10 and 12 match their reference hashes.
The board measured steps 37 and 38 together, in run-5de0cb146d0e, on a slow box: 144.5 ms at 41.4 MB, while track C’s unchanged code drew 45.9 ms in the same run, against 25.2 ms in the one before, and track D’s 147.7 ms, against 122 to 132 ms. A second run of the same code, run-0ea6dd17c4d2 (with track C’s step 36), drew 129.1 ms at 39.6 MB.
Step 39: the checks on huge pages, and the sample summed as it comes in
After step 37, 2.0 M dTLB load misses remained, 45% of them at the BOOL triggers’ prefetch of their checks: 40,710 checks on seed 1, 1.63 MB, too little for a huge page of their own.
-
The checks on huge pages. One helper,
huge, now allocates both the term table’s slots and the grouped checks: alone, at a 2 MiB boundary, never freed,MADV_HUGEPAGEbefore the writes andMADV_COLLAPSEafter them, as in step 37. Its size is rounded up to whole 2 MiB pages, as a huge page maps only a whole aligned 2 MiB of a block: a block of 1.63 MB got none. The counting sort writes the checks straight into it (group_into).perf stat -r 3, three alternating rounds: dTLB load misses 2.49 to 2.59 → 0.41 to 0.47 M, dTLB store misses 0.28 to 0.30 → 0.21 M, page faults 16,646 to 16,674 → 16,237 to 16,268, cycles 3,401 to 3,502 → 3,444 to 3,455 M, instructions 6,273 → 6,271 M. -
The sample summed as it comes in. Each thread adds its part of the sample’s counts to the sum under a lock as soon as it has counted, and frees it. Before, the main thread joined all the parts first, then summed them and freed them one by one, 0.56 ms after the last part was counted; now the sum is ready 0.03 ms after it (a build with timestamps, medians of 10 runs).
-
The counting sort from the back.
group_intocounts into an array written when allocated, so the counts’ loads find no shared zero page (step 16), and puts the items in last first, each key’s end moving back to its start, so the starts need no rotation.
In the timing build (medians of 10 runs), the walks begin at 14.78 ms instead of 15.36, and the passes end at 131.81 ms instead of 133.87.
Local, against step 38 (ab.py, 20 alternating runs on the P-cores, on AC, load average 2 to 6),
six rounds: medians 137.54, 137.87, 136.85, 137.32, 137.11 and 137.23 → 134.96, 135.30, 136.33,
135.57, 135.05 and 135.66 ms, minimums 135.87, 136.16, 135.55, 136.13, 136.14 and 136.46 →
133.38, 134.02, 134.19, 134.09, 133.95 and 134.47 ms. memory.peak over 28 alternating runs:
median 41.45 → 41.59 MB, highest 42.84 → 43.72 MB, as the checks’ block takes 2.10 MB where
they took 1.63. S 763 → 769. Gate: 510 pass, 0 fail; seeds 2, 3, 7, 10 and 12 match their
reference hashes.
Step 40: the checks grouped while the table is marked
After step 39, once its threads have planned the queries, the plan took 2.45 ms more on the main thread alone (a build with timestamps, medians of 10 runs): grouping the phrases 0.30 ms, the checks’ block and the checks’ grouping 0.36 and 0.79, the term flags 0.06, the stores 0.26, marking the term table 0.50 and the frees 0.19.
The checks now go to a thread of their own, which allocates their block and groups them, while the main thread groups the phrases, flags the terms, numbers the stores and marks the table. Marking needs every term’s flags, so a term’s BOOL flag now comes from the checks’ lists, set for each check’s key, instead of from the grouped checks. In the same build, the plan’s tail takes 1.76 ms instead of 2.45: the helper is done 1.36 ms after it starts, its block taking 0.49 ms and its grouping 0.88, while the main thread groups the phrases in 0.51 ms, spawn included, flags the terms in 0.29, numbers the stores in 0.27 and marks the table in 0.52, so the join waits for nothing. The walks begin at 14.19 ms instead of 14.89.
Local, against step 39 (ab.py, 20 alternating runs on the P-cores, on AC, load average 4 to 8),
six rounds: medians 135.68, 135.60, 135.16, 135.64, 135.55 and 136.89 → 134.71, 134.42, 134.22,
135.07, 134.36 and 135.32 ms, minimums 134.42, 134.50, 133.46, 133.46, 133.90 and 134.23 →
133.51, 133.10, 132.99, 132.92, 132.88 and 133.19 ms. memory.peak over 40 alternating runs:
median 41.62 → 41.76 MB, highest 43.34 → 44.33 MB, the next highest 43.36; nothing allocated
changes, only the thread that allocates the checks’ block. S 769 → 774. Gate: 510 pass, 0 fail;
seeds 2, 3, 7, 10 and 12 match their reference hashes.
Step 41: the walk’s probes in registers, and a block’s tokens split at its LFs
After step 39 the pass ran 6,132 M instructions on seed 1, and two loops took most of its
cycles: the walk, which keys, hashes and prefetches each token (28% of the samples), and the line
end’s token loop (34%). The walk loaded eight values from the stack at each token, three of them
the header of the Vec of probes, whose length it also stored back at every push.
- The walk keys the tokens. Both callers gave [
walk] the same token callback, a key and a prefetch pushed to aVec. The walk now does that itself and passes each line’s probes to its one callback as a slice. They sit in a buffer that each block first grows, if it must, to 32 entries past the line’s tokens so far, the most that one block ends, so the buffer’s address and the count stay in registers and the push tests no capacity: 5 instructions instead of 11. - The ids left out at the line end. Every line starts with its id, which reads as a token. The walk compared every token’s start with the line’s start to skip it; the line end now takes the line’s tokens from the second on.
- A block’s ends split at its LFs. The token loop tested at each token whether an LF came
before it. A token never spans an LF, so the block’s ends are now taken one line at a time:
those up to the next LF, its own bit included, with one mask (
lfs ^ (lfs - 1), which takes all of them when the block holds no LF). The token loop tests no LF, and the line end, now called from one place, is inlined into the walk. - The key fold in two steps. A key ORs 0x20 into each of its 32 bytes, which lowercases a letter and leaves a digit as it is, and then masks off the bytes past the token: two vector operations instead of four.
Built up on step 39 (perf stat -r 5, two rounds): the fold, instructions 6,132.1 → 6,053.5 M,
cycles 3,270 and 3,282 → 3,267 and 3,267 M; the walk keying the tokens, 5,936.5 M, 3,199 and
3,199 M; the ids left out, 5,886.6 M, 3,164 and 3,219 M; the ends split at the LFs, 5,794.5 M,
3,167 and 3,165 M, and branch misses 16.63 → 16.29 M.
Local, against step 39 (ab.py, 41 alternating runs on the P-cores, on AC, load average 5 to 6),
two rounds: medians 135.79 and 135.36 → 132.35 and 131.44 ms, minimums 133.76 and 133.45 →
129.75 and 130.03 ms. memory.peak over 8 alternating runs: median 41.42 → 40.71 MB, highest
42.97 → 42.06 MB. S 774 → 763 (on step 39’s code, 769 → 758). Gate: 510 pass, 0 fail.
The board ran steps 40 and 41 together, run-ff1ae2c91791 (commit f17de2c), 126.9 ms; a second run of the same code, run-9f07c5db9176 (commit ca86ea9, which changed only track C), drew 124.4 ms, 42.7 MB and 76.5 points.
Step 42: the walk’s token loop in a call of its own
After step 41, the walk’s token loop, inlined into scan‘s loop together with the line end,
kept four of its values on the stack: the block’s token starts, the hash’s shift, the slots’
address and the chunk’s address. It loaded them at every token and stored the starts back, 38
instructions per token, as the line end’s values held the registers across the whole loop
nest.
- A call per line.
Tokens::lineruns the token loop up to the next line end, never inlined, and returns the line’s token count; the walk keeps the block’s state between lines (its offset, its token starts, token ends and LFs not taken yet, the next token’s start, and whether it ends in a token), 250,000 calls on seed 1. In a function of its own, the token loop keeps every value in a register: 31 instructions per token, none of them a stack access. - The window’s bound in a register.
chunk.get(start..start + MAX_TERM)also tested whetherstart + MAX_TERMwraps around. LLVM had ruled that out while the block’s offset came from a loop over the chunk, but not once it comes from the walk’s state: 6 instructions per token for the test.key_innow testsstart < chunk.len() - 31(saturating), against a bound computed once: 2 instructions. - The walk ends where the next block would start past the chunk, which ends in LF, so it needs no test of its own for the last line.
Built up on step 41 (perf stat -r 5): the call per line, instructions 5,796.0 → 5,517.0 M,
cycles 3,182 → 3,070 M; the bound in a register, 5,373.9 M, and cycles 3,109 → 2,997 M in that
round; as committed, 5,382.2 M. Against step 41, two rounds: instructions 5,796.0 → 5,382.2 M,
cycles 3,132 and 3,135 → 2,961 and 2,972 M, branch misses 16.28 → 16.32 M.
Local, against step 41 (ab.py, 41 alternating runs on the P-cores, on AC, load average 4.7 to 7.7
with a browser taking half of one P-core, so the minimums are the steadier figures), two rounds:
medians 132.05 and 137.28 → 127.15 and 132.88 ms, minimums 129.20 and 129.46 → 124.29 and
124.14 ms. memory.peak over 8 alternating runs: median 41.25 → 40.71 MB, highest 42.02 → 41.94
MB. S 763 → 777. Gate: 510 pass, 0 fail.
Step 43: a phrase candidate tested on one more term first
After step 42, the phrase triggers of seed 1’s documents led to 1,028,628 (trigger, phrase)
candidates, of which 19,427 match, 1.9%. Each loaded its phrase’s bounds and terms from
Queries, two arrays read at random, and compared the terms in a loop whose length varies: 4.1%
of the cycle samples and 5% of the mispredicted branches.
The plan now keeps, beside each phrase’s query and the trigger’s position in it, the position and id of one more of its terms: the first, or the second when the trigger is the first. The pass compares that term with the document’s term at the same place, which its own list of terms holds, and loads the phrase only when they agree: for 25,843 candidates, 2.5%. The plan’s phrase entries take 16 bytes instead of 8, 304 KB in all.
Against step 42 (perf stat -r 5, two rounds): instructions 5,382.2 → 5,339.3 M, cycles 2,961
and 2,972 → 2,875 and 2,877 M, branch misses 16.32 → 15.48 M.
Local, against step 42 (ab.py, the rounds of step 42): medians 127.15 and 132.88 → 125.81 and
124.51 ms, minimums 124.29 and 124.14 → 120.68 and 120.62 ms. memory.peak over 12 alternating
runs: median 41.45 → 41.80 MB, highest 42.50 → 43.21 MB. S 777 → 782. Gate: 510 pass, 0 fail.
Step 44: each token’s checks prefetched
After step 43, the BOOL triggers’ loop at a line’s end stalled on its load of check_at[t], the
start of the trigger’s range of checks: a 303 KB array read at random, 3.9% of the cycle samples.
The line end’s token loop, which finds each token’s slot in the term table, now prefetches that
token’s entry, so it has started to load by the time the triggers’ loop reads it. The same
prefetch did not pay on step 41 (see below); since step 42 the token loop runs in a call of its
own and no longer spills for it.
Against step 43 (perf stat -r 5, three rounds): instructions 5,339.3 → 5,412.1 M, cycles 2,909,
2,909 and 2,912 → 2,832, 2,893 and 2,863 M, branch misses 15.47 → 15.46 M.
Local, against step 43 (ab.py, 41 alternating runs, four rounds, the first two on a build that
differs only in line numbers): medians 122.97, 122.00, 121.81 and 121.81 → 121.92, 121.03, 121.53
and 120.87 ms, minimums 120.28, 120.95, 120.08 and 120.67 → 119.65, 119.76, 119.83 and 119.23 ms.
memory.peak over 8 alternating runs: median 41.88 → 42.38 MB, highest 43.71 → 43.15 MB. S 782 →
783. Gate: 510 pass, 0 fail.
Step 45: the probe stops at a taken home slot
After step 44, perf record on seed 1 (turbo off): 15.46 M mispredicted branches, tma_bad_speculation
17.1% of the slots, and 22% of those mispredicts on the probe’s first test, the one branch that
ends a probe at the term or an empty slot. A count of where each token’s probe ends: of the
7.56 M tokens that are no query term, 5.39 M found their home slot empty and 2.17 M found it
taken (1.33 M one slot on, 0.49 M two, 0.35 M three or more); of the 28.72 M term tokens, 27.63 M
found their term at home and 1.08 M further on. So the 3.25 M probes that went on past their
home slot mispredicted, and two thirds of them belonged to tokens that are no term at all.
Slot::MORE.internsets it on a term’s home slot when it stores the term further on, and a term met again keeps it. At the home slot, [TermTable::find_from] stops when the slot holds the key or has noMORE, in one branch, as the probe’s own test is, and returns flags of 0, the empty slot’s, when it stopped at another term. An empty slot has noMORE, so that test also stops at it. Only a slot that is some displaced term’s home sends a probe on: 4.5% of the slots at the table’s 29% load, instead of 29%. A slot’s flags hold the term id times 32 now, so a term id stays below 2^27.#[inline(always)]. With its first slot peeled off the loop,find_fromwas no longer inlined into the pass or the sample: instructions 5,412 → 6,629 M, cycles 2,900 → 3,150 M. Cargo.toml allows clippy’sinline_alwaysfor it, which costs no line.- The long bit in one shift.
Slot::tailset its top bit fromkey[1] >> 32 != 0, six instructions per token. A key’s every byte has bit 5 set ([fold]), so bit 37 ofkey[1]is set exactly when the key runs past 12 bytes, and(key[1] >> 6) as u32 & 1 << 31moves it into place; the long test is that bit too, and the long key’s load takes no bounds check.
perf stat -r 5, interleaved, two rounds, step 44 → MORE → both: instructions 5,412.1 →
5,466.2 → 5,360.1 M, cycles 2,902 and 2,897 → 2,811 and 2,804 → 2,778 and 2,784 M, branch misses
15.46 → 12.56 → 12.57 M. Hashing the key’s first word only, instead of the XOR of two, would save
another 72 M instructions, but put more terms off their home slot: branch misses 12.57 → 12.74
M and cycles 2,747 → 2,763 M, so it did not stay.
Local, against step 44 (ab.py, 41 alternating runs on the P-cores, turbo off), MORE alone,
two rounds: medians 120.83 and 120.27 → 117.71 and 117.45 ms, minimums 118.79 and 118.76 →
116.47 and 116.14 ms. Then step 44, MORE alone and both, two rounds: medians 120.62 and 120.62
→ 117.33 and 117.42 → 116.42 and 116.37 ms, minimums 118.63 and 119.33 → 116.19 and 116.09 →
115.47 and 114.82 ms. As committed (a build that differs only in line numbers), against step 44,
two more rounds under a higher load: medians 123.80 and 123.09 → 119.52 and 118.77 ms, minimums
121.34 and 120.32 → 117.37 and 116.13 ms. memory.peak over 6 alternating runs: median 39.1 → 39.9 MB, highest 40.9 →
40.0 MB, with the same allocations. S 783 → 800. Gate: 510 pass, 0 fail.
Step 46: a window’s sums from nibble tables
After step 45, Window::flush took 5 to 7% of the cycle samples, and about half of that went to the
sum in Tally::add_bits: per word of a query’s window, a popcount for its count and six masked
popcounts for the sum of its bits’ positions (bit_index_sum), 1,773 queries on sets times 61
windows. LLVM vectorized them with pshufb, a table lookup per nibble for each of the seven.
[window_cell] does the window in 16 steps of four words, with AVX2. Two lookups per nibble give
each byte’s bit count and the sum of its bits’ places in the byte (a third table, for the high
nibble, adds 4 per bit to the second). sad adds the counts and the places per word, and
maddubs and madd weigh each byte’s count by its offset in the word, 0 to 56, leaving each
word’s total in two 32-bit halves. A multiply adds each word’s offset in the window times its
count, and the window’s first id times the whole count comes in at the end. The window’s
positions add up to less than 2^32, so the halves never carry into each other. The function is
unsafe, as Check::matches and classify are, and takes one SAFETY comment at its call.
Against step 45 (perf stat -r 5, interleaved): instructions 5,360.1 → 5,264.2 M, cycles 2,763
and 2,769 → 2,656 and 2,677 M on a first form of the same code, and 2,770 → 2,730 M as committed;
branch misses unchanged (12.6 M). Part of the cycles saved come from the vector ports that the
other hyperthread’s token loop leaves idle, so the wall moves less than the cycles.
Local, against step 45 (ab.py, 41 alternating runs, on a box with a load average of 3 to 4 from
other work): the first form, four rounds, medians 122.41, 118.78, 119.17 and 119.52 → 120.71,
117.86, 117.57 and 117.99 ms, minimums 117.65, 117.41, 117.05 and 116.87 → 117.06, 116.02, 115.58
and 115.99 ms; as committed, two rounds, medians 120.49 and 118.39 → 120.41 and 117.05 ms,
minimums 117.53 and 116.36 → 115.91 and 114.73 ms. memory.peak over 5 alternating runs: median
40.0 → 39.7 MB, with the same allocations. S 800 → 819 (the first form, with its tables as
_mm_setr_epi8 calls and tuples that rustfmt splits, cost 35). Gate: 510 pass, 0 fail.
Step 47: phrase triggers without a branch
After step 46, the line end’s token loop still pushed each phrase trigger’s position to a Vec
behind a test of the slot’s PHRASE flag: the one branch on what a token is that it kept, and
the Vec’s length, loaded and stored at each push, the one value of the loop on the stack.
Step 9 had measured a branch-free push as a loss, when the trigger lists were Vecs. Since
step 31 the token loop writes its runs into one slice with cursors, so the positions now go to a
fifth run of kept, a store and an add per token like the other four, and the phrase checks
read that run. One line fewer.
Against step 46 (perf stat -r 5, interleaved, two rounds): instructions 5,264.2 → 5,305.6 M,
branch misses 12.63 → 11.61 M, cycles 2,719 → 2,706 M in the round without an outlier.
Local, against step 46 (ab.py, 41 alternating runs, load average 5 to 7 from other work), four
rounds: medians 120.51, 119.23, 118.19 and 117.84 → 118.32, 118.01, 117.17 and 117.19 ms, minimums
117.50, 116.63, 116.03 and 116.29 → 115.37, 115.46, 115.66 and 115.34 ms. memory.peak over 5
alternating runs: median 40.2 → 37.8 MB, one Vec fewer per thread. S 819 → 818. Gate: 510
pass, 0 fail.
Step 48: the first matches in half the memory
A build that sampled the cgroup’s memory.current and memory.stat every 20 µs from a thread of
its own, with /proc/self/smaps at the phase ends, on seed 1 (local medians 39.8 to 40.8 MB, in two
modes 2 MB apart). Memory rises from 16 MB when the plan is ready to 27 MB as the walks start
(per thread 400 KB of query cells, 326 KB of check cells, the window’s rows and lists), then
climbs to 39 MB through the walks, and peaks either late in the walks or as the threads group
their first matches, about level. What climbs is Tally::first: about 121,800 (query, doc) pairs
per thread, 976 KB each, 11.7 MB on 12 threads, the largest piece of the peak. At the peak the
cgroup held 36.5 to 38.9 MB of anonymous memory, 1.1 MB of kernel memory (0.74 MB of page tables)
and no file pages. Of the anonymous memory, 6 or 8 MB sat on huge pages: the term table’s 4 MB
and the checks’ 2 MB, as meant, and in the higher mode one more 2 MB page under the term keys
(TermTable::keys, 4.9 MB, calloced, of which only 13 entries, the terms longer than 12
bytes, are ever written). THP is always on this box, so the first write into a 2 MiB-aligned
stretch of that block faults in a whole huge page when one is free.
- The first matches a doc at a time. The pairs of one doc come together, 3.7 per doc on
average (32,700 runs for 121,800 pairs per thread), so
firstnow holds the query indices alone,u32, and after each doc’s, its id marked with the top bit ([DOC]):Tally::markat the end ofadd_checks, which runs once per doc, after its phrases; and after each first match of a query on sets, whose docs come out of order at the window’s end. Grouping reads the list from the back, where a doc’s id comes before its queries, through the same counting sort, which now takes its items as an iterator from the last to the first. 154,500 entries of 4 bytes per thread instead of 121,800 of 8: 618 instead of 976 KB. - The keys off huge pages.
MADV_NOHUGEPAGEon the keys’ block: 13 pages of 4 KB instead of, in most runs, a 2 MB huge page.
Local, against step 47: memory.peak over 5 to 6 alternating runs, three sessions: medians 40.0,
40.85 and 39.8 → 33.8 and 33.7 MB with both changes, 37.9 MB with the keys alone (37.5 to 39.1
against 37.5 to 41.2). ab.py, 41 alternating runs, four rounds (the first two on a build identical
but for formatting): medians 116.99, 117.29, 117.51 and 117.49 → 116.33, 116.58, 116.68 and 117.01
ms, minimums 115.09, 115.58, 115.33 and 115.76 → 114.79, 115.16, 115.06 and 115.30 ms. S 818 →
841. Gate: 510 pass, 0 fail. Step 47’s memory median, 40.2 → 37.8 MB, was most likely the keys’
huge page coming and going.
Step 49: memory is at its cap in B, so spend it on time
The board’s run of step 48 had memory.peak 37.6 MB against 43.3 MB for step 47, and its points fell
(77.40 → 77.16). The memory factor is min(M_ref / M, 50)^0.20, and B’s reference used 2,200 MB
(harness/calibration-seed1.json), so any peak under 44.0 MB already earns the cap. Across four
board runs (steps 45 to 48, 37.6 to 43.3 MB), K · T^0.5 · S^0.15 is the same, 32.3: the memory
factor did not move. Step 48’s 23 lines bought nothing in B.
This step undoes step 48’s first-match list (S 841 → 818) and keeps its other part, the two lines
that keep the long terms’ keys off huge pages, which take about 2 MB off a typical run. It then
spends some of the room under the cap on time: DENSE_SHARE 48 instead of 32, so terms held by one
sampled document in 33 to 48 become bitsets. Measured on step 44, that was -1.1% in four rounds
for +0.85 MB.
Full seed 1, step 47 → step 49, ab.py, 41 interleaved runs, medians / minimums: 118.95 /
115.45 → 116.45 / 113.25 ms and 118.12 / 115.67 → 115.96 / 113.58 ms (-2.1%, -1.8%).
memory.peak (systemd-run, alternating): 40.2, 37.6, 40.6 → 39.8, 39.6, 39.1 MiB, under the cap
with about 2 MB to spare at the board’s usual reading. S 818 → 820. The gate passes (510 of 510).
Step 50: the probes carry their slots’ addresses
After step 49, the line end’s token loop, which probes each token’s home slot
([TermTable::find_from]) and marks the doc’s terms, ran 57 instructions per token, 7 of them
stack accesses. For the probe that goes on past its home slot, the loop held the slots’ address,
their count’s mask and the long keys’ address, so it reloaded the addresses of check_at, seen
and kept from the stack at every token, and kept the phrase triggers’ cursor there, a load and a
store per token; LLVM also hoisted the slow path’s reloads of the slots’ address and mask above
the probe’s branch.
- The slot’s address in the probe. [
TermTable::prefetch] returns the home slot’s address instead of its index, and the walk stores it beside the key, so the probe loads its slot with no shift and no table address. The walk’s token loop takes the same number of instructions. - Past the home slot out of line.
TermTable::find_pasttakes the probes that go on past a home slot,#[cold]and never inlined. Only the call needs the table, so the token loop keeps every value but two in registers: 52 instructions per token, 3 of them stack accesses (the address ofcheck_at, and the lists’ cursor, loaded and stored), as only the six registers a call preserves hold values across it.
perf stat -r 5, interleaved, two rounds: instructions 5,191.3 → 4,949.2 M (-4.7%), cycles 2,652
and 2,647 → 2,591 and 2,588 M (-2.2%), branch misses 11.41 → 11.40 M. The address alone: 5,078.3 M
instructions, cycles 2,650 and 2,647 → 2,596 and 2,595 M.
Local, against step 49 (ab.py, 41 alternating runs on the P-cores, turbo off), medians /
minimums: seed 1, 113.31 / 111.51 → 111.27 / 109.58 ms and 113.30 / 111.73 → 111.50 / 110.06 ms;
seed 2, 114.00 / 112.49 → 111.92 / 110.26 ms and 114.09 / 112.50 → 111.80 / 110.44 ms (-1.6% to
-2.0%). memory.peak over 5 alternating runs: 38.6 to 39.8 → 38.8 to 39.6 MiB, with the same
allocations. S 820 → 826. Gate: 510 pass, 0 fail.
Step 51: a short key’s tail as it is
After step 50, each probe built the key’s tail ([Slot::tail]) before comparing it with the
slot’s: its bytes 8 to 11 and, in the top bit, whether it runs past 12 bytes, four instructions
per token. The probe branches on that same long bit anyway, for the long keys’ full compare, and
LLVM had already split found & long into a branch on long first. On the short side the top
bit is 0, so [TermTable::holds] now compares the low half of key[1] with the slot’s tail as
it is, and builds the tail only on the long side. Same answers: a short key’s tail is that low
half. The loop takes two instructions fewer per token, as the new layout jumps over the long
side at every token. One line fewer.
Against step 50 (perf stat -r 5, interleaved, two rounds): instructions 4,949.7 → 4,875.4 M
(-1.5%), cycles 2,585 and 2,584 → 2,536 and 2,541 M (-1.8%), branch misses 11.40 → 11.38 M.
Local, against step 50 (ab.py, 41 alternating runs), medians / minimums: seed 1, 111.29 /
109.86 → 109.85 / 108.60 ms and 111.45 / 110.06 → 110.11 / 108.09 ms; seed 2, 113.15 / 110.19 →
110.80 / 109.11 ms and 111.90 / 110.24 → 110.68 / 109.06 ms (-1.1% to -2.1%). memory.peak over 3
alternating runs: 38.5 to 39.5 → 39.1 to 40.0 MiB, with the same allocations. S 826 → 825. Gate: 510
pass, 0 fail.
Step 52: the rows’ bits set without bounds checks
After step 51, the line end’s loop that sets the doc’s bit in the row of each of its terms kept
in rows, bits[store[t]][i / 64] |= 1 << (i % 64), took 9 instructions per term, two of them
bounds checks: one on store[t] and one on the row. A term id is below store.len(), and a term
with the ROW flag has a store below the row count, so both reads go unchecked. 1 more line.
Against step 51 (perf stat -r 5, interleaved, two rounds): instructions 4,875.4 → 4,832.1 M
(-0.9%), cycles 2,546 and 2,545 → 2,522 and 2,518 M (-1.0%).
Local, against step 51 (ab.py, 41 alternating runs), medians / minimums: seed 1, 109.66 /
108.43 → 109.38 / 107.66 ms, and 109.70 / 108.57 → 109.04 / 107.80 ms as committed; seed 2,
110.41 / 108.89 → 109.55 / 108.26 ms; seed 3, as committed, 110.22 / 108.37 → 110.13 / 107.86 ms
(-0.1% to -0.8%). The same allocations. S 825 → 826. Gate: 510 pass, 0 fail.
Step 53: 37 fewer lines, the same pass
Cuts in code that runs once or once per thread; the hot loops are as they were:
- The parse. A thread’s share of the lines is a
Queries<Key>, the same layout as the merged queries with each term still its key, so theLinesstruct goes, and the merge offsets each part’satinstead of summing a per-query length (-8). A malformed line’s error comes fromok_or_else(-1). - The plan. A term’s cost is a
u32that fits on one line (-2); the per-thread plans are unzipped in a statement of their own (-1); a BOOL query’s check is compiled first and kept when no cover term is common (-1); the store and row counts share onelet, and the row and list counts are one field,sizes(-3); the term flags areu32, andTermTable::mark’s loop, now onefor_eachwithout casts, sits where it runs, inPlan::new(-5);Plan::phrasesjoins the otherimpl Plan(-2). - The rest. One
useline (-3);MADV_DONTNEEDnamed in a comment at its call, like the other advice values (-2);key_hashinsideTermTable::home, its only caller (-2); the sample makes each new part the sum and adds the old sum into it, with no branch for the first part (-3);intern’s push on one line, and the sample’s and the scan’s per-thread locals declared together (-4).
Against step 52 (perf stat -r 5, interleaved, three rounds, seed 1): instructions 4,829.8 →
4,828.4 M (the plan and the sample), cycles 2,525, 2,480 and 2,523 → 2,488, 2,525 and 2,523 M.
Local, against step 52 (ab.py, 41 alternating runs), medians / minimums: seed 1, 109.13 /
107.73 → 108.83 / 107.13 ms; seed 2, 109.46 / 108.24 → 109.47 / 107.76 ms; a second round, seed
1, 109.10 / 107.69 → 109.15 / 107.64 ms; seed 3, 110.02 / 108.60 → 109.79 / 108.02 ms. memory.peak
over five alternating runs: median 39.9 → 39.5 MB. S 826 → 789. Gate: 510 pass, 0 fail.
Step 54: the rows from the docs’ term bits, 64 docs at a time
Of the 36.28 M tokens of seed 1, 28.72 M are query terms, and 11.11 M of those are a doc’s first
of a term kept in a bitset row. Each paid a store into the rows run of kept and a cursor add in
the token loop, then at the line end a load of its term’s store and a read-modify-write of one
bit in a 512-byte row, at random among about 540 rows. The doc’s seen bits already hold the
same facts, one bit per term id.
So the plan, right after the sample, renumbers the terms: the common ones (543 on seed 1, of
which 532 have a row) take ids 1 up, and a common term in a set query keeps the row of its id.
The others follow in their old order. hits, lens, the long keys and the queries’ terms move
to the new ids at once; the slots take theirs in the pass that marks them, which runs anyway.
A doc’s rows are then the first ceil(rows / 64) words of seen (9 on seed 1). The line end
copies them into Window::group, one word per block of 64 rows, and the 64th doc transposes each
64 × 64 block (six vectorized steps) into word i / 64 of its 64 rows and zeroes it. The pass’s
end spills the last, partial 64. A common term in no set query keeps a row nobody reads.
Against step 53 (perf stat -r 5, interleaved, two rounds, seed 1): instructions 4,828.4 →
4,676.3 M (-3.1%), cycles 2,523 and 2,523 → 2,424 and 2,426 M (-3.9%), branch misses 11.4 →
11.2 M. The renumbering takes under 1 ms on the main thread before the plan.
Local, against step 53 (ab.py, 41 alternating runs), medians / minimums: seed 1, 109.06 /
107.61 → 106.50 / 105.33 ms; seed 2, 110.26 / 108.56 → 107.60 / 105.87 ms (-2.4%).
memory.peak over five alternating runs: median 38.7 → 38.8 MB (the rows round up to a multiple
of 64, and each thread keeps 4.6 KB of blocks). S 789 → 823. Gate: 510 pass, 0 fail.
Step 55 (reverted): the terms interned while the queries are parsed
Reverted to step 54’s code after three board runs: 104.1, 103.9 and 120.4 ms (run-dc45dd0a1279, run-3dca0206aaaf, run-001fa0eb6f48) against step 54’s 101.1 and 100.4 ms, although it was 0.76% faster locally over nine rounds. The first two board runs came in a spell when D also ran 20% slow; in the third, A, C and D ran at their usual times. Below is the step as it was measured.
A timeline of step 54 (a build with timestamps, ms since main, medians of 12 runs, seed 1,
turbo off, 12 threads on the P-cores). Only the main thread works from 2.3 to 6.0 ms and in the
plan’s tail, and only it and one more from 9.9 to 11.9:
| From | To | What | On |
|---|---|---|---|
| 0.12 | 0.82 | 12 parse threads spawned, the last at 0.82 | main |
| 0.25 | 1.68 to 2.29 | the queries parsed, about 1.45 ms a share | 12 threads |
| 2.31 | 3.15 | the term table set up: its huge pages’ faults and zeroing 0.68, MADV_COLLAPSE 0.17 | main |
| 3.15 | 5.98 | 152,904 term occurrences interned, 18.5 ns each | main |
| 5.98 | 8.01 | the sample: spawned by 6.11 to 6.32, counted in 1.05 to 1.35 ms a thread, 0.22 ms from the last sum to the join | 12 threads |
| 8.01 | 8.87 | the renumbering: the partition 0.25, the id map 0.23, hits and lens 0.21, the long keys 0.06, the queries’ terms 0.08 | main |
| 8.94 | 9.86 | the queries planned, 0.6 ms a share, joined 0.13 ms after the last | 12 threads |
| 9.86 | 11.93 | the plan’s tail: the checks’ block 0.47 and grouping 0.88 on their thread; the phrases 0.6 (the spawn included), the flags 0.32, the stores 0.29 and marking the slots 0.84 on main | 2 threads |
| 11.93 | 12.21 | the plan’s lists freed | main |
| 12.31 | 13.14 to 13.68 | 12 scanning threads spawned by 12.51, each 0.8 to 1.2 ms setting up (Tally::new 0.6 to 0.9) | 12 threads |
The largest serial piece is the intern, and the table it needs took 0.84 ms more on the main
thread while the other threads had nothing to do. The table’s size needs only the term count,
and a term follows every space but those before an operator, the only capitals after a space,
exactly for every line that parses (checked on all 510 gate inputs). So 11 threads now parse,
while the main thread counts the terms (one pass over pairs of bytes summed in u32, 0.2 ms)
and sets up the table; it then joins the shares in order and interns each as soon as it is
parsed, so the ids stay in file order. A line that does not parse stops the parse, as before;
an invalid line counts zero or more terms, so the table holds every term of the shares that
parse. In the same build, interleaved with step 54 (12 runs each): the table is ready at 2.07 ms
instead of 3.02, the intern ends at 5.12 instead of 5.87, the plan at 10.94 instead of 11.89,
the walks start at 12.00 to 12.44 instead of 13.09 to 13.80, and the output is written at 102.60
instead of 103.62 ms.
Local, against step 54 (ab.py, 41 alternating runs), medians / minimums, nine rounds: seed 1,
106.51 / 104.86 → 105.41 / 104.33 ms; seed 2, 106.85 / 105.29 → 106.28 / 104.70 ms; seed 3,
106.73 / 105.75 → 106.05 / 104.50 ms; seed 1, 106.63 / 105.23 → 105.57 / 104.24 ms; seed 1,
106.50 / 105.09 → 106.02 / 104.34 ms; seed 3, 106.94 / 105.02 → 106.02 / 104.86 ms; seed 2,
106.64 / 105.09 → 105.74 / 103.96 ms; seed 4, 107.80 / 106.00 → 106.58 / 105.30 ms; seed 1,
106.15 / 105.17 → 105.77 / 104.41 ms: -0.36% to -1.13%, -0.76% on average, so a trial.
memory.peak over five alternating runs: median 39.2 → 39.0 MB. S 823 → 829. Gate: 510 pass,
0 fail.
Step 56: the probe without a branch on a key’s length, and the triggers’ loop unchecked
Where the pass goes, measured on step 55’s code, whose pass is step 54’s (perf record of cycles,
instructions and branch misses on the profiling build, seed 1, turbo off; perf stat: 4,678.8
M instructions, 2,424 M cycles and
11.13 M mispredicted branches, 129 instructions and 67 cycles per token). Counted by a build
with counters: 36.28 M tokens, 28.72 M of them query terms, 22.24 M a doc’s first of a term,
7.18 M BOOL triggers, 1.75 M first sights of a listed term, 0.92 M phrase triggers, 12.94 M
checks, and 1.37 M probes past the home slot (find_past).
| Stage | Cycles | Instructions | Mispredicts |
|---|---|---|---|
Tokens::line: token ends, keys, hashes, prefetches | 26.9% | 30.8%, 39.7 a token | 37% |
| The line end’s token loop: probes, seen bits, runs | 26.7% | 31.7%, 40.9 a token | 1% |
find_past | 3.8% | 1.4% | 17.6% |
| The BOOL triggers’ loop | 5.4% | 5.9%, 38 a trigger | 3.7% |
add_checks | 11.6% | 7.5%, 27 a check | 3.5% |
seen cleared, first matches | 4.6% | 3.6% | 10.2% |
| The lists’ pushes and the phrases | 5.4% | 1.9% | 3.6% |
flush and spill | 6.4% | 4.6% | 7% |
The two token loops run at about 2.2 instructions per cycle on each of a core’s two threads, so
what they cost is mostly their instructions. In Tokens::line, most mispredicts are the exit
of the per-block loop over a block’s 9.1 token ends on average, about once per block.
- The probe’s first test. [
TermTable::find_from] compared a key’s bytes 8 to 11 with the slot’stailand branched first on whether the key runs past 12 bytes, for which it built the long bit and compared the whole key: abt, a branch and a jump over the long side at every token. It now XORs the key’s whole second word with thetail, zero-extended. A key past 12 bytes has bytes 12 to 15 that are not zero and never matches there, nor does a term past 12 bytes, whosetailhas its top bit set. [TermTable::intern] gives such a term’s home slotMORE, andfind_pastnow starts at the home slot itself, with the full compare ([TermTable::holds], as before). Seed 1 has 13 such terms, and 0.19% of its tokens run past 12 bytes. Instructions 4,474.6 → 4,294.4 M, cycles 2,416, 2,386 and 2,418 → 2,354, 2,351 and 2,356 M, branch misses the same (11.2 M), over three interleaved rounds ofperf stat -r 5. The same with the line at 12 or more bytes, which kept a key of exactly 12 bytes off the first test too: 4,333.6 M instructions but 12.6 M branch misses and the same cycles, as seed 1 has 3,809 terms of exactly 12 bytes (of 75,747). - The triggers’ loop. It loaded
check_at[t]andcheck_at[t + 1]with a bounds check each, wrote its four indices totodobehind two more, and took the range’s length through two conditional moves, about 38 instructions per trigger with four values reloaded from the stack. The two entries are now one unchecked[u32; 2]load, the four indices one store, and the cursor moves on by the range’s length, which a loop past the first four fills: the ranges of a doc’s triggers are disjoint, sotodo’s 4 spare entries cover the store. Instructions 4,678.8 → 4,474.6 M (-4.4%), cycles 2,398, 2,423 and 2,425 → 2,392, 2,390 and 2,417 M: the loop waits on its loads ofcheck_atmore than it runs.
Both parts were built and measured on step 55’s code first, then moved onto step 54’s when step
55 was reverted; neither touches what step 55 changed. Against step 54 (perf stat -r 5,
interleaved, three rounds): instructions 4,676.2 → 4,291.4 M (-8.2%), cycles 2,397, 2,425 and
2,427 → 2,361, 2,358 and 2,359 M (-2.3%), branch misses 11.2 M both. ab.py, 41 alternating
runs, medians / minimums: seed 1, 106.62 / 105.06 → 104.17 / 102.96 ms; seed 2, 106.85 / 105.30
→ 105.47 / 103.73 ms and 106.92 / 105.63 → 104.94 / 103.49 ms; seed 3, 107.14 / 105.17 → 105.31 /
103.38 ms; seed 1, 106.40 / 104.74 → 104.25 / 103.08 ms; seed 3, 107.07 / 105.20 → 105.09 / 103.92
ms (-1.3% to -2.3%, -1.8% on average, so a trial). On step 55’s code, against step 55: seed 1,
105.90 / 103.26 → 103.11 / 101.92 ms; seed 2, 106.40 / 104.50 → 103.71 / 102.82 ms; seed 3,
106.56 / 105.30 → 104.13 / 103.04 ms; the triggers’ loop alone, seed 1, 105.67 / 104.56 → 105.24 /
104.21 ms, seed 2, 106.48 / 105.01 → 106.05 / 104.70 ms. memory.peak over five alternating runs:
38.2 to 39.9 → 38.4 to 40.2 MB. S 823 → 821. Gate: 510 pass, 0 fail.
Step 57: the id lists from one log, sorted at the flush
After step 56, a build that skipped the id lists’ pushes (wrong answers, to size the stage) ran
137 M fewer cycles (-5.9%, the flush’s lists included), and perf record of L2 misses put 27%
of the pass’s 6.6 M on the pushes: about one per push. Seed 1 has 1.75 M of them, a doc’s first
sight of a listed term, about 7 per document, 28.7 K per window. Each loaded the term’s store,
then one of 3,452 Vec headers, then wrote the end of that list: the ends of thousands of lists
lie at random, and few stay in L2 between two pushes.
Now a document’s entries go to the end of one log, list j holding document start + i as
the u32 j << 5 | i % 32, and the log records where each 32 documents’ entries end. At the
flush, a counting sort moves them into the lists: a count per list, the sums, and a scatter in
log order, so that each list stays ascending; the lists are then ids[at[j]..at[j + 1]]. The
log, 115 KB a window on seed 1, is written in order, and the sort’s 13.8 KB of counts stay in
L1. An entry of a u64, j << 16 | i, needs no ends, but its log took 2.5 MB more at the
peak (memory.peak 41.2 to 41.3 MB) for the same cycles.
Against step 56, measured after the reboot of Nov 1 with turbo off: perf stat -r 5,
interleaved, instructions 4,291.4 → 4,318.8 M (+0.6%), cycles 2,364 and 2,365 → 2,301 and 2,302
M (-2.7%), branch misses 11.2 → 11.0 M. ab.py, 61 alternating runs, medians / minimums: seed
1, 103.47 / 102.07 → 101.56 / 99.99 ms; seed 2, 103.31 / 102.04 → 100.98 / 99.90 ms; seed 3,
103.56 / 101.78 → 100.92 / 99.69 ms (-1.8% to -2.5%). The same build before fmt merged two
lines: seed 1, 103.49 / 102.11 → 101.20 / 99.56 ms; seed 2, 104.00 / 101.76 → 101.33 / 99.89
ms; seed 3, 103.70 / 101.90 → 100.90 / 99.78 ms (-2.2% to -2.7%). Against step 54, seed 1:
105.58 / 104.06 → 101.47 / 99.69 ms (-3.9%). memory.peak over five alternating runs: 38.6 to 40.1
→ 38.2 to 40.0 MB. S 821 → 842. Gate: 510 pass, 0 fail.
Step 58: the most frequent term of each home slot moved into it
A probe that finds its term at the home slot stops there; any other goes on in find_past, out
of line, with a mispredicted branch at its loop’s end (3.9% of the cycles). On seed 1 that was
1.46 M probes (the sample’s included), 1.17 M of them for a term that sits further on: the
terms land in file order, so the first of those with the same home takes it, however rare.
[TermTable::settle] now visits each home slot with MORE before the slots are marked, and
moves into it, of the terms of 12 bytes or less whose home it is, the one with the most sample
hits: terms with the same home lie in one run of slots from it, as does a term in a home slot
not its own, which can move on to any later slot of the run, so either pair can trade places.
MORE stays with the slot. Probes past the home slot: 1.46 → 0.82 M, of which 0.53 M find a
term (the less frequent of two that share a home). Taking only terms with the same home as the
one there, and no term out of a home not its own: 0.84 M, about the same cycles.
On the main thread after the marking, the pass took 0.75 ms, and the wall gained 0.8% to 0.9% (seeds 1 to 3, 100.38 / 99.23, 100.50 / 99.16 and 100.26 / 97.78 against 101.33 / 99.50, 101.34 / 99.97 and 101.21 / 99.68 ms). It now runs on a thread of its own while the main thread groups the phrases, flags the terms and numbers the stores (1.2 ms), on the old ids, whose sample hits it reads through the renumbering.
Against step 57: perf stat -r 5, interleaved, instructions 4,318.8 → 4,279.9 M, cycles 2,304
and 2,300 → 2,256 and 2,256 M (-2.1%), branch misses 11.0 → 10.1 M. ab.py, 61 alternating
runs, medians / minimums: seed 1, 101.82 / 100.08 → 100.20 / 98.82 ms; seed 2, 102.41 / 100.24 →
100.31 / 97.84 ms; seed 3, 100.86 / 99.44 → 99.67 / 98.25 ms; seed 1, 101.26 / 99.77 → 99.72 /
98.34 ms (-1.2% to -2.1%, -1.6% on average, so a trial). The same change before its lines were
tightened: seed 1, 101.50 / 100.32 → 99.71 / 98.29 ms; seed 2, 101.09 / 99.98 → 99.52 / 97.59
ms; seed 3, 101.23 / 99.53 → 99.72 / 98.06 ms. memory.peak over five alternating runs: 39.2 to 39.5
→ 39.0 to 39.7 MB. S 842 → 864. Gate: 510 pass, 0 fail.
Step 59: the probe’s first test as one select, and no prefetch of check_at
find_from went on to find_past unless found || !more, two sete, an or and a test
behind an empty asm block that kept LLVM from making two branches of it, and the flags’ select
then tested found once more. Now on is the key’s difference when the slot has MORE and 0
otherwise, one cmov, and the branch tests it: two instructions fewer per token in both token
loops. Alone, against step 58: instructions 4,279.9 → 4,243.1 M, cycles 2,256 to 2,262 → 2,202 to 2,232
M; ab.py, 61 alternating runs, seed 1, 99.17 / 98.15 → 98.37 / 97.24 ms; seed 2, 99.13 / 98.16
→ 98.53 / 97.17 ms (-0.6% to -0.8%).
The token loop at the line end also prefetched each token’s check_at entry for the BOOL
triggers’ loop (step 44), and with every register taken it reloaded check_at‘s address from
the stack for it, per token. Without the prefetch: 65 M fewer instructions (1.8 per token), and
the triggers’ loop now waits on loads of check_at that are mostly L2 hits; cycles 2,216 to 2,235
→ 2,193 to 2,221 M on top of the select. After step 56 the prefetch’s removal alone was within the
noise (below).
Against step 58: perf stat -r 5, interleaved, instructions 4,279.9 → 4,178.0 M, cycles 2,255
and 2,255 → 2,220 and 2,217 M (-1.6%), branch misses 10.1 M both. ab.py, 61 alternating runs,
medians / minimums: seed 1, 99.64 / 98.41 → 98.34 / 97.12 ms; seed 2, 99.63 / 98.42 → 98.14 /
96.67 ms; seed 3, 99.19 / 98.14 → 97.71 / 96.19 ms; seed 1, 99.91 / 98.40 → 98.06 / 96.77 ms;
seed 2, 99.75 / 98.32 → 98.23 / 97.05 ms (-1.3% to -1.9%, -1.5% on average, so a trial). memory.peak over five alternating runs: 38.8 to 39.7 → 38.3 to 39.4 MB. S 864 → 863.
Gate: 510 pass, 0 fail.
Step 60: the corpus faulted in during the intern, and the chunks freed during the write
A timeline of step 58 (step 59 changed only the token loop), in a build with timestamps as in
step 55’s section (ms since main, medians of 12 runs, turbo off), and of this step in the same
build, interleaved with it:
| What | Step 58, seed 1 | Step 60, seed 1 | Step 58, seed 2 | Step 60, seed 2 |
|---|---|---|---|---|
| the queries parsed | 2.15 | 2.03 | 2.07 | 2.17 |
| the term table set up (main only) | 3.01 | 2.92 | 2.97 | 3.10 |
| the terms interned (main only) | 5.95 | 5.76 | 5.86 | 5.95 |
| the sample joined | 7.62 | 7.48 | 7.79 | 7.73 |
| renumbered (main only) | 8.45 | 8.34 | 8.57 | 8.49 |
| planned | 9.37 | 9.30 | 9.68 | 9.41 |
| the plan’s tail ends (3 threads) | 11.48 | 11.22 | 11.64 | 11.37 |
| the walks start | 12.76 to 13.24 | 12.42 to 12.83 | 12.97 to 13.56 | 12.59 to 13.00 |
| a walk takes | 75.15 to 76.01 | 74.01 to 75.32 | 74.91 to 76.01 | 74.01 to 74.67 |
| the walks end | 87.78 to 89.99 | 86.34 to 89.19 | 87.73 to 89.85 | 86.50 to 88.82 |
| the scanning threads’ tails end | 91.85 to 93.86 | 90.44 to 92.68 | 92.19 to 93.67 | 90.49 to 92.29 |
| formatted | 95.22 | 94.09 | 95.10 | 93.62 |
exit called | 95.81 | 94.76 | 95.75 | 94.26 |
| the process gone | 97.28 | 95.77 | 97.39 | 95.14 |
From the parse to the walks, only the main thread works for 3.8 ms (the table and the intern) and 0.9 ms (the renumbering), and three threads for 1.9 ms (the plan’s tail). At the end, the walks end 2.1 to 2.6 ms apart (medians of the spread), and every scanning thread’s tail takes 3.9 to 4.8 ms: the last one’s, on step 58, is the corpus pages dropped 0.72, the flush 0.53, the window freed 0.92, the merge 0.33 and its first matches grouped 1.61 (placing them 1.08). The exit takes 1.55 to 1.65 ms, against 0.13 for a process that exits at once.
The walk’s first touch of each 64 KiB of the mapped corpus is a page fault even when the file
is cached: the fault maps the 16 pages around it. Seed 1 draws about 3,900 of them, some 2.7 µs
each, in the middle of the walks. So, as soon as the queries are parsed, answer_all starts
threads / 4 threads (3 of 12) that read the corpus a byte per 64 KiB, each a third of it, and
are never joined. They run from 2.06 to 2.09 to 5.45 to 5.54 ms (seed 1), inside the intern, which
does not slow. With more of them, one shares the main thread’s core and the intern slows. A
walk takes 1.0 ms less. The faults are as many (17,320 → 17,337 a run, perf stat -r 10, two
rounds), but kernel cycles go 159.0 and 158.4 → 145.7 and 145.3 M. After step 38, helper
threads reading a byte per 4 KiB page from the start, at nice 19, slowed the parse, the sample
and the plan by about 2 ms (its entry in the list below); these read 16 times fewer bytes, and
only while one thread works.
The chunks, which answer_all never freed (step 38), are now freed on a detached thread once
they are formatted, while main writes the output: the exit then has less to unmap, 1.65 →
1.10 ms (seed 1) and 1.55 → 0.94 ms (seed 2). Freed on the main thread, they took 0.84 ms and
saved 0.91 ms of the exit.
Local, against step 59 (ab.py, 61 alternating runs), medians / minimums: seed 1, 98.18 / 96.97
→ 96.73 / 95.55 ms; seed 2, 98.08 / 96.44 → 96.60 / 95.22 ms; seed 1, 97.88 / 96.53 → 96.78 /
95.36 ms; seed 2, 97.94 / 96.96 → 96.49 / 94.54 ms (-1.1% to -1.5%). Before, against step 58:
seed 1, 99.84 / 98.22 → 97.97 / 96.89; seed 2, 99.34 / 98.51 → 98.18 / 97.14; seed 1, 101.63 /
98.33 → 99.68 / 96.72; seed 2, 99.58 / 98.19 → 98.41 / 96.73 (-1.2% to -1.9%). First measured
on step 54, against it: seed 1, 105.58 / 104.39 → 104.06 / 102.57; seed 2, 106.14 / 104.31 →
104.66 / 102.39; seed 1, 105.61 / 104.12 → 103.88 / 102.59; seed 2, 105.12 / 103.95 → 103.46 /
102.16 (-1.4% to -1.6%); the prefaulting alone, three rounds: seed 1, -0.95%, -1.39%, -0.95%;
seed 2, -0.78%, -0.34%, -1.31%. memory.peak over five alternating runs, seed 1: 38.8 to 39.4 →
39.4 to 40.2 MB, median 39.3 → 39.7. S 863 → 868. Gate: 510 pass, 0 fail.
Step 61: a zero in a register for the line end’s selects, and four instructions fewer per token in the tokenizer
The token loop at the line end takes three cmovs against 0 per token, and LLVM set a register
to 0 before each (mov $0), as none was free to hold one across the loop. A zero made once per
line behind an empty asm block, which the optimizer cannot see through, now stays in a
register for all three: 43 M fewer instructions. Alone, on step 59: cycles 2,216 to 2,226 → 2,204
M (-0.8%); ab.py, 61 alternating runs, seed 1, 98.13 / 96.86 → 97.52 / 96.06 ms; seed 2,
97.97 / 96.68 → 97.41 / 96.03 ms; seed 3, 97.96 / 96.56 → 97.15 / 95.89 ms (-0.6% to -0.8%),
under the bar alone. On step 60: 4,178.7 → 4,135.8 M instructions, cycles 2,225 and 2,221 →
2,213 and 2,205 M.
Tokens::line took 28 µops per token, three of them for a token past 32 bytes, which is rare.
Before the length test, the loop set a register to the key of 0xFF bytes (vpcmpeqd) for every
token, so that the test could jump straight to where both paths meet; and the mask’s address
took a mov of the table’s address and a sub of the length. The length test is now marked
cold (std::hint::cold_path), so that the 0xFF key is set on its own path only, and fold
takes the length negated, start - end, so that the mask’s address is that plus a constant,
folded into the vpand: 74 M fewer instructions, 2 per token. Then the token’s start and end,
each base plus a bit’s position, are offsets from the block instead: the start of a token
open since an earlier block lies below 0, wrapped, and moves back 64 per block, and the test
that a token’s 32 bytes lie in the chunk compares, signed, against a bound fixed within a block.
25 M fewer instructions; short of registers, LLVM keeps the block’s address on the stack and
loads it per token.
perf stat -r 5, interleaved, seed 1, instructions and cycles (M):
| Build | instructions | cycles |
|---|---|---|
| step 60 | 4,178.7 | 2,225, 2,221 |
| the key’s length test and mask only | 4,104.5 | 2,198, 2,204 |
| the zero only | 4,135.8 | 2,213, 2,205 |
| both | 4,061.6 | 2,178, 2,185 |
| step 60, again | 4,178.7 | 2,222, 2,225 |
| both, and the offsets (this step) | 4,037.1 | 2,159, 2,161 |
On seed 2: 4,179.6 → 4,038.1 M instructions, cycles 2,189 → 2,161 M. Branch misses 10.1 M in all.
ab.py, 61 alternating runs, medians / minimums, step 60 → this step: seed 2, 97.69 / 96.00 →
95.58 / 93.42 ms; seed 1, 96.64 / 94.94 → 94.65 / 93.10 ms; seed 3, 96.32 / 94.81 → 94.22 /
92.51 ms; the same code before its comments: seed 1, 96.55 / 94.96 → 94.70 / 92.76 ms; seed 3,
96.27 / 94.86 → 93.72 / 92.56 ms (-1.9% to -2.6%, -2.2% on average). Without the offsets: seed
1, 96.30 / 95.11 → 94.88 / 93.36 ms; seed 2, 96.71 / 95.08 → 95.05 / 93.37 ms; seed 3, 96.01 /
94.68 → 94.90 / 93.50 ms; seed 2, 96.52 / 95.26 → 94.96 / 93.22 ms (-1.2% to -1.7%).
memory.peak over five alternating runs, seed 1: 39.2 to 39.7 → 39.1 to 40.1 MB, median 39.5 both.
S 868 → 877. Gate: 510 pass, 0 fail.
On the board (run-280052ffeb2c) this step drew 97.9 ms against step 60’s 95.2 ms, but the same run was slow on every track: D 123.1 ms against 118.4 and A 16.9 ms against 16.65, with C unchanged. A 2% step is below what one board run resolves, so it stays on the local measurements above.
Step 62 (reverted): a doc’s runs packed 8 tokens at a time, and the home slot from the key’s first word
Reverted to step 61’s code after two board runs: 105.4 and 106.3 ms (run-e89cc599f8ef, run-63da3c47097b) against step 61’s 97.9 and 95.1 ms, although it was 2.7% faster locally over five rounds, measured on battery power. In the first run A, C and D ran within 2% of their usual times; in the second, A ran 42% and C 23% slow. Step 61’s code, back on the board, ran 98.1 ms (run-35a813ada612) in a run where A and C ran 4% and 7% slow, so step 62 cost about 7% there. Below is the step as it was measured.
perf record of step 61 (seed 1, turbo off): the line end’s token loop is 37 instructions per
token and 24% of all cycles, at 2.6 instructions per cycle on each of a core’s two threads, so
its cost is its instructions. Twelve of the 37 kept the four runs of kept: four stores, the
three cursors’ tests and adds, and the select of the flags of a term new in the doc.
The loop now stores one value per token: the slot’s flags, the term’s id times 32 and its
flags, with LISTED and BOOL dropped by the select when the doc already held the term. Then
[pack] takes the doc’s tokens 8 at a time: the 8 flags shifted down make the ids, and for each
run the flag shifted to each lane’s top bit makes an 8-bit mask, whose entry in a 256-entry
table (2 KB, built at compile time) is the permutation that moves the marked lanes to the front;
one store writes them at the run’s cursor, which moves on by the mask’s popcount. The lists and
BOOL runs take the ids, the phrase run the positions. A store writes 8 entries, so each run starts
8 past the room of the last, and the 8 entries past the doc’s tokens are zeroed, as the last load
reads them. The token loop is 27 instructions, the packing 34 per 8 tokens, with no branch but
the loop’s exit, once per doc (+0.28 M mispredicts). The table’s permutation built per mask by
pdep and pext instead took about 7 instructions more per run and 8 tokens: 4,037.1 → 3,986.0 M
instructions, cycles the same as step 61 (2,137 and 2,142 → 2,139 and 2,139 M).
[TermTable::home] hashed the exclusive or of the key’s first two words, a vpshufd and a
vpxor before the vmovq in the tokenizer, per token. It now multiplies the first word alone:
terms whose first 8 bytes agree share a home slot, and [TermTable::settle] moves the most
frequent into it. Mispredicts +0.16 M, from the probes past it.
perf stat -r 5, interleaved, instructions, cycles and branch misses (M):
| Build | instructions | cycles | branch misses |
|---|---|---|---|
| step 61 | 4,037.1 | 2,118, 2,132 | 10.12 |
| the packing only | 3,892.7 | 2,106, 2,109 | 10.41 |
| the packing only | 3,892.7 | 2,111, 2,111 | 10.40 |
| the packing and the hash | 3,823.2 | 2,096, 2,090 | 10.56 |
| step 61, seeds 1, 2, 3 (cycles: means of two) | 4,037.1, 4,038.1, 4,040.4 | 2,161, 2,159, 2,153 | 10.11 |
| this step, seeds 1, 2, 3 (cycles: means of two) | 3,823.2, 3,823.1, 3,825.9 | 2,073, 2,079, 2,084 | 10.56 |
ab.py, 31 alternating runs, medians / minimums, ms. The packing only, against step 61: seed 1,
94.21 / 92.92 → 92.09 / 90.75; seed 2, 94.42 / 93.15 → 92.85 / 91.68; seed 1, 94.60 / 93.26 →
92.98 / 91.01; seed 2, 94.80 / 93.58 → 92.69 / 91.18; seed 3, 93.84 / 92.91 → 91.91 / 90.30; seed
1, 94.68 / 93.19 → 92.43 / 91.78; seed 1, 96.86 / 94.50 → 95.12 / 92.60; seed 3, 95.95 / 94.23 →
94.09 / 92.68 (-1.6% to -2.4%, -2.0% on average). Three-way, step 61, the
packing only and this step: seed 1, 94.88 / 93.27, 92.74 / 91.31 and 91.91 / 90.91; seed 3, 94.32
/ 93.07, 92.61 / 91.09 and 91.85 / 90.05. This step against step 61: seed 2, 94.63 / 92.91 →
91.94 / 90.75; seed 1, 94.45 / 93.18 → 92.55 / 91.01; seed 3, 94.46 / 93.11 → 91.82 / 90.49 (-2.0%
to -3.1% over five rounds, -2.7% on average). memory.peak over five alternating runs, seed 1:
39.1 to 39.5 → 39.5 to 40.0 MB, median 39.5 → 39.6. S 877 → 901. Gate: 510 pass, 0 fail.
Step 63 (trial): step 62’s packing alone
Step 62 put two changes on the board at once and ran about 7% slower there than step 61. The
packing is computation on the line end’s own data; the hash of the key’s first word alone puts
terms that share their first 8 bytes on one home slot, so more probes go past it into the term
table. This step keeps the packing and step 61’s hash, to tell on the board which of the two cost
the time. Locally, on battery, the packing alone measured -1.6% to -2.4% against step 61 over eight
ab.py rounds (step 62’s section). Gate: 510 pass, 0 fail. S 877 → 901 (static_axes).
Step 66: step 64’s parallel intern again
Step 64’s one board run, run-bb4ed7d47695 (93.4 ms), came in a run where A, C and D read 1.5 to 3.4%
above their best, so it did not show whether the change pays on the box. Re-measured today on
step 63’s code (local, turbo off, ab.py, 41 interleaved runs): seed 1 median 94.76 → 92.01 ms
and, in a second session, 95.05 → 92.26 ms; seed 3 93.94 → 91.22 ms, -2.9%. Gate: 524 pass, 0
fail, now with unseen full seeds 51 to 54. S 901 → 961 (static_axes). The first push meant to carry
it, 9c3eb3c, lost the source file to a reset of the working tree before the commit and carried
step 65’s code instead, so this is its first board trial since step 64. It was to be kept only if its
board runs beat step 63’s 90.6, 91.1 and 92.9 ms. Its run, run-33959bbbe488, read 87.3 ms, in a
run where A and C read 3.1% and 0.5% above their best: 3.6% below step 63’s best run. Kept.
Experiments that did not stay
-
After step 63, 32-byte aligned checks, a branch-free
add_checksand immediate vector shifts inpack(pushed as 052ab6e). Local, turbo off,ab.py, 41 interleaved runs, seed 1: median 95.05 → 94.54 ms (-0.5%, inside the runs’ spread). The board counted S 901 → 956, about 0.19 points, more than the time could return. Its two board runs (step 65): run-e40ad8747964, 94.4 ms, in a run where A, C and D read 14 to 43% above their best, and run-4d543d6cf37e (pushed as 9c3eb3c), 95.6 ms, where C and D read 1.6% and 3.4% above theirs. Not kept: B went back to step 63’s code. -
After step 63, where the time goes, measured for three redesigns (local, turbo off, on AC, seed 1, step 63’s binary). The question was whether a larger change could make B 10% faster locally, the least a board trial would need to show through the box’s noise (steps 62 and 64).
perf stat -r 5: 104.2 ms ±5.7%, 4,111 M instructions, 2,355 M cycles (1.75 per cycle), 10.8 M branch misses, 9.09 M loads that missed L2 (0.25 per token of the 36.3 M), 0.38 M that missed L3, 0.33 M page walks. Top-down: retiring 52.9%, bad speculation 14.7 (branch mispredicts 13.2), back end 19.3 (memory 8.9, core 10.4), front end 13.1.- Sampled on the event itself: 87% of the L2 misses fall in the scanning loop’s line end. Of
the branch misses, 36% are one branch, the tokenizer’s
while line != 0: it exits once per block, after as many ends as the block’s text holds, so no history predicts it. The probe’s two tests (find_from,position) take 15%; the rest spread over the line end’s loops, none above 3%. Cycles by source line: none above 5.8%. - A timeline from 5 kHz samples (the
profilingbuild): the scan starts at 15.3 ms. The first 16 ms hold 603 samples where 12 busy CPUs would give 960, idle time worth about 6 ms of the scan on all 12 CPUs, which then runs to 93 ms. - The three redesigns, each against the share it could remove: a term table small enough for
L2, at most the 8.9% memory share; a line end batched by the kind of term, already the
branch-free token loop of steps 41-47, its remaining misses loop exits whose counts follow
the text, about 5% at most; the scan started during the plan, at most the 6 ms idle.
Step 64’s parallel intern is the largest piece of the last one, re-measured today with
ab.py, 41 interleaved runs: seed 1 median 94.76 → 92.01 ms, seed 3 93.94 → 91.22 ms, -2.9%. No combination came near 10%, so none was built.
-
After step 62, the tokenizer’s hash constant (seed 1,
perf stat -r 5, interleaved, two rounds). The multiply’s 64-bit constant takes a register, so the tokenizer reloads its block’s address from the stack per token. Freeing it:- A constant that fits a sign-extended 32-bit immediate,
0xFFFF_FFFF_9E37_79B1, so thatimultakes it inline: the block’s address then stays in a register, but a short key’s product is small, and negated it has its top bits all set, so short keys pile into a few home slots: 3,823.2 → 40,959.0 M instructions, branch misses 10.6 → 31.4 M. _mm_crc32_u64(0, key[0]), the hash’s top bits shifted down from 32: the block’s address stays in a register, but axorzeroes the accumulator per token. Instructions 3,823.2 → 3,813.5 M, cycles 2,089 and 2,088 → 2,084 and 2,087 M, branch misses 10.57 → 10.50 M._mm_crc32_u64(key[0], key[0]), the key as its own accumulator: one instruction, but a linear map of too low a rank, 192,796 M instructions and 46.6 M branch misses.
- A constant that fits a sign-extended 32-bit immediate,
-
After step 62, the probes 32-byte aligned. The tokenizer’s 32-byte store of a key takes the most cycle samples of its loop, and at a 40-byte stride 3 in 8 of them cross a cache line. As a
#[repr(align(32))]struct of 64 bytes, none does: instructions 3,823.2 → 3,827.6 M, cycles 2,095 and 2,093 → 2,116 and 2,111 M (+0.9%), the larger buffer costing more than the splits. -
After step 62, the time outside the walks (local, turbo off, on battery; timelines from a build with timestamps on step 61’s code, seed 1, medians of 12 runs, ms since
main;ab.pyon step 62’s code, 25 or 31 alternating runs, medians / minimums, ms):- The timeline: parsed 2.17, table set up 3.04, interned 5.86, sample joined 7.53, renumbered
8.39, planned 9.31, the plan’s tail ends 11.21, the scanning threads start setting up at
11.74 to 12.06 and walk from 12.48 to 13.11, the walks end at 84.48 to 87.67, the tails at
88.55 to 90.71, formatted at 92.05, written at 92.65;
ab.py’s wall 95.77. At the exit 21.7 MB is still mapped (18.5 MB anonymous), with 688 KB of page tables and 89 mappings. - Ranked by walk end, the first thread to end its walk took 4.9 ms over its tail and the last 3.4 ms: the walks end over 2.8 ms (84.10 to 86.93) and the tails over 1.4 ms (88.99 to 90.36). The last thread’s tail: corpus pages dropped 0.89, last flush 0.43, window freed 0.08, merge 0.22, first matches grouped 1.41 (allocations 0.13, counting 0.21, placing 1.00, the list freed 0.08). The format threads start 0.08 to 0.24 ms after the join and take 0.93 ms each. Over 12 runs each of the 12 chunks was the last to end its walk in some run, so no static split of the corpus evens the walks out.
- The last walk to end leaving its corpus pages to the exit (a counter passed to
scan), 4 more lines: seed 1, 92.79 / 90.67 → 92.61 / 90.78 and 92.03 / 91.27 → 91.95 / 90.94; seed 2, 92.50 / 91.29 → 93.19 / 91.13 and 92.38 / 90.97 → 92.71 / 91.40, within the noise. The drop moved out ofscan, after the grouping, the last one again skipped: seed 1, 95.30 / 93.97, seed 2, 96.60 / 93.62, +2.7% and +4.4%. - Each format thread’s output reserved once, 64 bytes a line, instead of grown, with the same lines: seed 1, 92.03 / 91.27 → 91.90 / 91.13, 92.38 / 90.80 → 91.89 / 90.42 (31 runs) and 91.96 / 90.90 → 92.23 / 90.54; seed 2, 92.38 / 90.97 → 92.09 / 90.96 and 92.43 / 91.37 → 92.13 / 90.85: -0.2% on average, within the noise; memory.peak median 39.5 → 39.6 MB over five alternating runs; gate 510 pass. With the plan and the queries also freed on the thread that frees the chunks: seed 1, 91.86 / 91.00, seed 2, 92.16 / 91.04.
- Not built: the terms deduplicated by each parse thread before the intern, as seed 1’s 12
shares hold 115,788 distinct terms between them against 152,904 occurrences, so the main
thread would intern 24% fewer for a table per parse thread; and an intern on every thread
into the shared table by compare-and-swap, each thread taking ids
t + threads * kand the renumbering skipping the gaps, about 3 ms off the start for some 30 to 40 lines, which then also needs the term table set up during the parse (step 55) and the prefaulting threads moved out of the intern’s time.
- The timeline: parsed 2.17, table set up 3.04, interned 5.86, sample joined 7.53, renumbered
8.39, planned 9.31, the plan’s tail ends 11.21, the scanning threads start setting up at
11.74 to 12.06 and walk from 12.48 to 13.11, the walks end at 84.48 to 87.67, the tails at
88.55 to 90.71, formatted at 92.05, written at 92.65;
-
After step 61 (seed 1,
perf stat -r 5, interleaved;ab.py, 31 alternating runs, medians / minimums, ms):- On step 62’s packing, the probes holding the home slot’s offset in bytes instead of its
address, which the line end’s loop, with three cursors gone, has a register for: the
tokenizer’s
leaper token goes, 3,892.7 → 3,860.2 M instructions, but cycles 2,109 and 2,110 → 2,086 and 2,120 M, and seed 1, 92.98 / 91.01 → 93.44 / 91.70; seed 2, 92.69 / 91.18 → 93.73 / 91.94. The tokenizer still reloads its block’s address from the stack per token.
- On step 62’s packing, the probes holding the home slot’s offset in bytes instead of its
address, which the line end’s loop, with three cursors gone, has a register for: the
tokenizer’s
-
After step 60 (on step 58,
ab.py, medians / minimums, ms; timelines from builds with timestamps, seed 1, medians of 12 runs):parallelas a tree: each thread spawns the upper half of its share and runs the lower half, so the last of 12 starts after 4 spawns, for 4 more lines. Withworkas adyn Fn, 61 runs, two rounds: seed 1, 98.73 / 97.02 → 98.37 / 95.13 and 98.02 / 96.62 → 98.25 / 96.12; seed 2, 98.51 / 97.00 → 98.08 / 96.20 and 97.93 / 96.22 → 97.75 / 96.15 (-0.4% to +0.2%). Generic overworkand aRange, scan’s line end compiles insideparallel’s last step instead of the spawned closure, and keeps 0 in a register for the probe’scmove: one instruction less per token, 4,280.6 → 4,242.4 M instructions, cycles 2,229 and 2,269 → 2,236 and 2,235 M. Four rounds (41 or 61 runs): seed 1, -2.3%, -1.2%, -0.9%, -1.0%; seed 2, -1.2%, -1.0%, -1.4%, -1.4%. On top of step 59 and this step it still saves the instruction (4,178.7 → 4,136.3 M, cycles 2,222 and 2,226 → 2,208 and 2,214 M), but the wall no longer moves: seed 1, 96.53 / 95.01 → 96.47 / 94.50 and 96.66 / 95.53 → 96.49 / 94.15; seed 2, 96.76 / 95.06 → 96.38 / 93.58 and 96.36 / 95.24 → 96.43 / 94.64. Not kept. The token loop sets a register to zero for each of three selects per token; held in a register across the loop, one of them would go.- The corpus pages dropped in pieces of 2 MiB or 512 KiB, so that the other threads’ frees, which wait on the memory-map lock while a drop holds it, get in between: the last thread’s window freed in 0.27 or 0.07 ms instead of 0.70, but its drop took 2.33 or 1.89 ms instead of 0.64, behind those frees; wall medians 98.66 → 98.72 and 99.99.
- A smaller sample,
SAMPLE_SHARE96 or 128 instead of 64 (41 runs): seed 1, 98.22 / 96.80 → 98.44 / 96.90 and 98.40 / 97.21; seed 2, 98.27 / 96.60 → 97.75 / 96.86 and 98.18 / 96.73. - Bounds on the intern (2.87 ms on step 58, wrong answers): without the length of each key
2.69 ms, without the
MOREflag on the home slot 2.69, without the long key’s store 2.93, without all three 2.46. The rest is the probe and the loop, about 100 instructions per occurrence with a dozen stack spills, and no single hot spot.
-
After step 59 (seed 1;
perf stat -r 5, interleaved;ab.py, 61 alternating runs, medians / minimums, ms):- The zero that step 61 holds in a register, for
add_checks’s select and its first-match cap too: cycles unchanged, as its loop then reloadedseen’s address from the stack. A long token’s key of 0xFF bytes held in a register: itsvpcmpeqdbecame a register move, cycles unchanged (step 61 moves it off the common path instead). - The probes’ room for 32 more tokens, tested once per block, grown by a cold function: 21 M fewer instructions, cycles 2,200 to 2,204 → 2,198 to 2,202 M.
- The probes holding the home slot’s offset instead of its address: the token loop then kept one of its cursors on the stack. Not timed.
- The gather masked to the real terms’ lanes, with a pad id of
u32::MAX, whose top bit drops its lane: +28 M instructions, cycles 2,212 to 2,218 → 2,225 to 2,230 M. - A line’s token count added once per block (the popcount of its ends), and the probes written through a pointer, so that the token loop keeps no count: 7 M fewer instructions, cycles 2,223 to 2,225 → 2,236 to 2,244 M.
- The phrase triggers’
phrase_atentries prefetched after the token loop, and their first phrase entries after the triggers’ loop: +7 M instructions, +0.3 M branch misses, cycles 2,220 → 2,240 to 2,246 M. - Of the 12.94 M checks run, 9.20 M hit (71%), and 4.59 M (35%) hold whenever their trigger
is present (
table & HAS[j] == HAS[j],jthe trigger’s lane), so that their gather tells nothing; 91% have four distinct terms or fewer. Not built: those checks without the gather (a second range per trigger would cost the triggers’ loop more), or two checks of four terms in one eight-lane gather.
- The zero that step 61 holds in a register, for
-
After step 58 (seed 1 unless noted;
perf stat -r 5, interleaved;ab.py, 61 alternating runs, medians / minimums, ms):- Where the loads wait, by source line: of the 6.0 M loads that miss L2,
add_checkstakes 40%, the phrase candidates’ loop 20% and the log’sstorelookup 16%; of the 38.7 M loads that hit a fill buffer (a load under way),add_checkstakes 35% and the probe’s slot load 26%. - The table’s slots marked by
threadsscoped threads, a share each, instead of on the main thread: seed 1, 99.84 / 98.64 → 99.55 / 98.42; seed 2, 99.54 / 98.37 → 99.31 / 97.80 (-0.3%), for 5 more lines. - Each doc’s checks run at the next doc’s line end, so that the lines its triggers prefetch
have a whole line of tokens to arrive: two of
seen,todoandkept, swapped per doc. Fill-buffer hits 39.0 → 51.7 M and L1 load misses 45.7 → 59.1 M, as the lines left L1 again before their use; cycles 2,255 to 2,259 → 2,250 to 2,283 M. With the triggers’ prefetches into L2 only (T1): 2,250 to 2,276 against 2,260 to 2,261 M. - The log’s entries without their
storelookup (wrong answers, as a bound): cycles 2,252 to 2,258 → 2,230 to 2,235 M (-1.0%). Too little for entries keyed by term id, whose counting sort at each flush would run over 75,748 starts instead of the 3,452 lists’.
- Where the loads wait, by source line: of the 6.0 M loads that miss L2,
-
After step 57 (
ab.py, 61 alternating runs, medians / minimums, ms):- Each scanning thread groups its 121,600 or so first matches at its end in 1.2 to 3.8 ms: 0.3 ms of page faults on the grouped ids, 0.1 to 1.4 ms allocating the 50,001 starts, 0.2 ms counting and 0.5 to 0.8 ms placing them. With no grouping at all (wrong answers): seed 1, 101.07 / 99.70 → 98.09 / 96.43. The first matches pushed into buckets of 256 queries instead, and each output thread grouping its buckets of every chunk into ten ids per query: seed 1, 103.32 / 100.65 → 106.08 / 102.99; seed 2, 103.33 / 99.70 → 104.72 / 102.20; and memory.peak 38.1 to 39.6 → 48.0 to 48.4 MB, with 196 growing vectors per thread.
- The corpus prefetched ahead of the walk, a line per block, 128, 512 or 4,096 bytes ahead: cycles 2,296 and 2,314 → 2,313 to 2,329 M, no change.
-
After step 56, the per-token work (
perf stat -r 5, interleaved, seed 1;ab.py, 41 alternating runs, medians / minimums, ms):- The probe’s miss test as a branch-free select in
find_from, the miss mask hidden from LLVM, which made branches of it: 22 to 33 M fewer instructions, cycles -0.5% at most and none on top of the 32-byte checks below. Seed 1, on step 55’s code, 104.05 → 103.75. - A token’s length clamped to 33 in
fold, with a 0xDF byte before the mask’s 0xFF bytes, so that a token past 32 bytes takes a key no term has without anOption: 74 M fewer instructions, cycles +0.3%; 104.05 → 104.15. - No prefetch of a token’s
check_atentry: 37 M fewer instructions, cycles mixed; 104.05 → 103.67, within the noise. - A [
Check] of 32 bytes, its query index moved to a vector of its own read only for first matches and at the pass’s end: 7 M fewer instructions, cycles 2,357 to 2,362 → 2,342 to 2,348 M (-0.6%). With it,check_atandphrase_atside by side, one prefetch per token for both: +16 M instructions, cycles -0.4% to -0.8% more; plus a prefetch loop over the phrase entries, +51 M instructions and +0.3 M branch misses for about -0.5%; with the term’s store as a third column, +95 M instructions, slower. The 32-byte checks with the pair, against step 56: seed 1, 104.85 / 103.12 → 104.23 / 102.44; seed 2, 105.79 / 104.12 → 105.37 / 103.63. On top of step 57’s log (itsu64form): cycles -1.6% (2,310 and 2,305 → 2,273 and 2,237 M), but seed 1, 102.86 / 101.58 → 102.52 / 101.59; seed 2, 103.02 / 101.99 → 102.70 / 100.88; seed 3, 102.93 / 101.35 → 102.84 / 100.88 (61 runs, -0.1% to -0.3%), for 8 more lines. - A prefetch of a first match’s
showncount inadd_checks: 20 M more cycles. The cap onshowndropped, the first matches extended unconditionally: 10 to 41 M fewer cycles, mixed, and about 3 MB more at the memory peak. - Bounds (wrong answers, to size each stage): with no phrase checks, 95 M fewer cycles (-4.1%); with no first matches counted, 125 M fewer (-5.4%), mostly their grouping in the tally.
- The probe’s miss test as a branch-free select in
-
After step 54, the serial start and the end of the pass (local, seed 1 unless stated; timelines from builds with timestamps, ms since
main;ab.pymedians / minimums, ms):- Prefaulting threads, by count (20 alternating runs each, one build, wall medians): none
105.62; 3 threads 104.05; 4, 104.30; 5, 104.42; 6, 104.89; 5 reading a byte per 4 KiB,
104.57; 5 started at
main’s start, before the parse, 106.87 (they slow the parse). Seed 2, 30 runs: none 105.56; 2 threads 105.39; 3, 104.35; 4, 104.48. 11 threads atSCHED_IDLE, 105.36; 5 atSCHED_IDLE, 104.55. MADV_SEQUENTIALon both mapped files, for a larger fault-around: 105.75 / 104.24 → 105.82 / 103.73 (41 runs).- Each format thread freeing its own chunk after a
Barrier, so that none frees a chunk another still reads: 105.92 / 104.40 → 106.75 / 104.89. Twelve threads unmapping at once contend for the memory-map lock and its TLB shootdowns. - The plan’s temporaries freed on a detached thread, on top of the prefaulting: 104.63 / 103.18 → 104.68 / 102.77.
- The scanning threads’ corpus pages not dropped (
MADV_DONTNEED) at the end of the walk: on the last thread to finish only, the wall 106.72 → 106.42 but the exit 0.22 ms longer; on the last two, 107.35; on all, 109.64. - Not built: the term table’s 4 MiB written a word per 4 KiB instead of whole would save about 0.12 ms of its 0.68; marking the slots on more threads at most 0.26 ms, as the grouping thread ends at 11.09 to 11.21 against the main thread’s 11.73.
- Prefaulting threads, by count (20 alternating runs each, one build, wall medians): none
105.62; 3 threads 104.05; 4, 104.30; 5, 104.42; 6, 104.89; 5 reading a byte per 4 KiB,
104.57; 5 started at
-
After step 55, the scanning threads’ setup (
ab.py, 41 alternating runs against step 55, medians / minimums, ms):- All of the tallies’ cells on huge pages ([
huge]), one block for the 12 tallies made by a helper thread during the plan’s tail, each scanning thread taking a readyTally: the walks start at 11.58 to 12.03 instead of 12.02 to 12.63 ms (the helper ends 0.2 ms after the tail), and the walks are a little shorter. Seed 1, 105.58 / 103.65 → 104.42 / 103.12; seed 2, 106.10 / 104.48 → 104.71 / 103.34; seed 1, 105.36 / 104.04 → 104.43 / 102.98; seed 2, 105.97 / 104.83 → 104.46 / 103.59; seed 3, 106.39 / 104.75 → 105.22 / 103.64: -0.9% to -1.4%. But memory.peak 38.8 → 44.2 MB. The peak falls at the end of the scans, where each tally’s check cells, a vector of their own, went back to the system at its merge; on huge pages they cannot, as a part of a huge page given back stays charged until the page is split, and the whole pages round 8.7 MB of cells up to 10.5. With the check cells in a block of their own, given back whole once every scan is done: 43.5 to 44.8 MB, as the peak comes before that. - Only the query cells on huge pages: 105.36 → 105.85 and 105.97 → 105.90, and +1.6 MB. Only the check cells: seed 3, 106.39 / 104.75 → 105.88 / 104.28, and +4.6 MB.
- The plan’s per-thread check lists freed on the grouping thread, which now owns them, with the BOOL flags set before it starts: in the timeline the plan ends 0.46 ms sooner, but seed 1, 105.67 / 104.71 → 105.83 / 104.82 and seed 2, 106.16 / 104.25 → 106.47 / 104.62. With the tallies also made on 4 KiB pages during the tail, by 12 threads the grouping thread spawns: 105.32 / 103.77 and 105.48 / 104.28, -0.3% and -0.6%.
- All of the tallies’ cells on huge pages ([
-
After step 54, more of the serial start (local, seed 1, builds with timestamps, ms since
main, medians of 10 to 12 runs, unless stated):- The terms counted on the main thread with
splitper line and astarts_withper line: 3.6 ms, as the 13th thread on 12 CPUs. Counted withfilter().count(), ausizeper pair: 0.44 ms against 0.23 for theu32sum on a quiet core, and the table ready 0.28 ms later. - The count and the table on a thread of their own, or each parse thread counting its share and sending it over a channel: the intern ends at 5.13 to 5.23 ms against 5.21, for 3 to 5 more lines. With 12 parse threads instead of 11, the count and the table competed for a CPU: 5.53 to 5.64 ms. With 10, 5.23 ms.
- The scanning threads’
Tallycells written during the plan’s tail, by 12 threads that the grouping thread spawns, each scanning thread taking one: its walk started 0.5 ms sooner, but the main thread’s tail ran 0.4 ms slower with the page faults beside it, andab.py(41 alternating runs, seeds 1 and 2) drew medians 106.04 and 106.26 ms against 105.94 and 106.21 without it, for 7 more lines. lenswritten at each id in an array sized likekeys, instead of pushed and cut back:parse_queriesalone, 40 times in a loop, 4.72 to 4.85 → 4.69 to 4.71 ms, for 2 more lines.- In a microbenchmark, 12 threads each writing 726 KB of new cells (a
Tally): the slowest took 0.81 ms; zeroed bycallocand faulted in byMADV_POPULATE_WRITE, 1.27 ms. A 4 MiB block on huge pages, one thread:allocandwrite_bytes0.71 ms,mmapand a write per page 0.59 ms; the kernel’s zeroing of the huge pages is most of it. - Not built: an intern on every thread, each taking the terms whose home slot is in its part of the table and deferring a probe that runs past it, then every thread reading its share’s ids back from the table. About 0.7 ms a thread against 2.9, but three parallel steps and their joins on the main thread, and about 40 lines.
- The terms counted on the main thread with
-
After step 53, the rows renumbered after the plan instead of before it. The same pass as step 54, but the plan numbered the rows first and then renumbered the checks (on the grouping thread, which sent the BOOL flags back over a channel), the phrases, the queries, the long keys and the stores. Seed 1, 108.98 / 107.70 → 106.88 / 105.37 ms, as fast as step 54, but S 789 → 845. Renumbering before the plan with new
keysand an extra pass over the slots: S 818, but 2.3 to 3.1 ms on the main thread, 1.5 ms slower than step 54. -
After step 53, the rows set from a per-doc log of events: each token’s flags pushed to one event list, walked at the line end. Instructions +186 M, cycles +1.4%.
-
After step 53, the rows’ read-modify-writes through a 64-doc buffer, without the renumbering (each row term’s bit gathered from
seenby its id): cycles the same, instructions +24 M. With the spill’s writes into the rows left out (wrong answers, as a bound) the cycles did not move either: the rows’ stores are not what costs, the per-term work is. -
After step 53, the phrases grouped on a thread of their own, and the sample’s
hitsreused for the renumbering: no change in the time to the end of the plan. -
After step 52, line cuts that moved the pass (local, seed 1,
perf stat -r 5). The scanning thread’s code is one function, so a cut in its cold start or end can change how LLVM allocates the hot loops’ registers. Each of these added instructions and was put back:Tally::take_firstinlined at its one call, 4,829.8 → 4,853.8 M (groupthen inlines into the scan);group_into‘s counts and prefix sums asfor_eachone-liners, 4,828.5 → 4,852.1 M, and 4,851.2 M withtake_firstkept out of line; the checks’ cells added to their queries’ by onefor_eachafter the walk, 4,828.5 → 4,856.8 M. In the walk’s token loop, the block’s first start dropped bystarts &= select_unpredictable(carry, !0, starts - 1): 4,828.7 → 4,832.9 M, cycles the same. Each would have saved 1 to 4 lines.#[target_feature(enable = "avx2")]cannot go either: the build’starget-cpudoes not make the intrinsics safe to call. -
After step 52, where the cycles and the wall go (local, seed 1, turbo off). Topdown: retiring 55%, bad speculation 14%, frontend 13%, backend 18%, of which memory about 8%; the kernel takes 6.6% of all cycles. A build with timestamps, in ms since
main: the queries are parsed and interned at 6.0 to 6.6, sampled at 8.7 to 8.9 and planned at 11.8 to 12.4, and the walks start at 12.8 to 13.5. A walk takes 85.6 to 89.5 ms, and the slowest chunk is a different one in each run (end spread 2.7 to 4.1 ms). The last thread’s tail takes 2.3 to 4.3 ms: last flush 0.4 to 0.6, the window’s free 0.2 to 1.5, merging the cells 0.2 to 1.0, grouping 1.1 to 2.4. Formatting then takes 1.5 ms and the write 0.5. Cycle cuts in the pass reached the wall at about a third or half of their size, as below. -
After step 52, frequent terms moved into their home slots. After the sample, a term stored past its home slot swaps with the term there when it was sampled in more documents. The swap keeps every probe’s run free of empty slots, and each slot keeps its
MORE. Term tokens probed past their home slot fell from 1.10 to 0.48 M; the rest are a long tail of terms whose home holds a more frequent term. Branch misses went 11.4 → 10.6 M, instructions 4,829.8 → 4,800.2 M, cycles 2,499 and 2,521 → 2,477 and 2,477 M. Run over all 262,144 slots, the settle took 1.57 ms on the main thread, the plan’s critical path, and the wall moved -0.2%. Over only the 11,026 slots the intern recorded, it took 0.18 ms.ab.py, medians / minimums: seed 1, 109.01 / 107.80 → 108.47 / 107.13 ms; seed 2, 110.11 / 107.92 → 109.80 / 106.95 ms; seed 3, 61 runs, 109.66 / 108.12 → 109.09 / 107.56 ms (-0.3% to -0.5%), for about 20 lines. -
After step 52, the rows’ loop (local, seed 1,
perf stat -r 5, interleaved; plainb-0drew 2,482 to 2,526 M cycles). The rows hold 532 of 75,748 terms, and a doc sets 45 bits in them. With the loop skipped (wrong answers), L1 load misses went 81.3 → 57.0 M and cycles fell 1.3% to 2.8%. With a row picked from the term id instead ofstore(wrong answers), L1 load misses went 81.3 → 70.6 M and cycles fell 0.5% to 1.0%. None of these paid:- Each row one line longer (576 bytes), so that a doc’s words in the rows spread over all 64 L1 sets instead of 8: L1 load misses 80.6 → 82.1 M, cycles 2,493 and 2,490 → 2,513 and 2,517 M. Held to 8 sets, the rows did not evict the rest of L1.
storebesidecheck_at, as oneVec<(u32, Store)>, so that the token loop’s prefetch ofcheck_atbrings each term’s store: L1 load misses 81.2 → 75.1 M. But the token loop then reloadedkept’s address and kept a second cursor on the stack: instructions 4,829.8 → 4,888.1 M, cycles 2,518 and 2,528 → 2,546 and 2,548 M.- The stores of a doc’s row terms prefetched before the BOOL triggers’ loop: L1 load misses 81.3 → 76.1 M, instructions +56 M, cycles 2,482 and 2,524 → 2,551 and 2,543 M.
-
After step 52,
check_at’s prefetch with another hint, T1, T2 or NTA instead of T0: cycles 2,525 and 2,524 M → 2,525 and 2,526 (T1), 2,525 and 2,523 (T2), 2,549 and 2,549 M (NTA). -
After step 52,
DENSE_SHARE56, 64 and 80 (ab.py, 41 alternating runs, seed 1): medians 109.02 → 108.92, 108.45 and 108.61 ms; 64 on seed 3 (61 runs): 109.66 → 109.22 ms (-0.4%), for about 1.9 MB more at the peak (step 44’s measure). -
After step 52, the tail’s blocks released by
MADV_DONTNEEDand never freed (the window’s bits, the check cells and the first-match list), so that nomunmaptakes the address space’s lock for writing, without reservingatandidsbefore the walk as the experiment after step 49 did: medians 110.60 → 112.26 and 109.25 → 110.32 ms (+1%). -
After step 51, token starts and ends relative to their block (local, seed 1,
perf stat -r 5, interleaved), so that the walk’s token loop adds no block offset to either andkey_inloads from the block’s address: instructions 4,875.7 → 4,887.2 M, as the loop then held the block’s offset as well as its address and kept the window’s bound on the stack. With the block’s address standing for its offset through the whole walk, 4,859.9 M and cycles 2,538 → 2,530 M, the bound still on the stack, as LLVM kept the chunk’s address and length in registers for the token near the chunk’s end; with that token’s key out of line, the call cost the loop its registers: 5,221.5 M instructions, cycles 2,634 M. -
After step 51,
classifyfrom two nibble tables (_mm256_shuffle_epi8, as simdjson does): per half block, a shift, a mask, two lookups, an AND and a compare instead of nine operations. Same answers (gate 510 of 510). Instructions 4,875.9 → 4,851.6 M, cycles 2,546 → 2,536 M over three rounds;ab.py, 41, 41 and 61 alternating runs on seeds 1, 2 and 3: medians 109.51, 110.53 and 110.30 → 109.36, 111.01 and 109.93 ms, for 4 more lines. -
After step 51, three more cuts in the line end’s token loop (local, seed 1,
perf stat -r 5, interleaved). The long keys’ side of the probe markedstd::hint::cold_path(), which dropped the jump that the short side took at every token: instructions 4,875.4 → 4,838.5 M, cycles the same over five rounds (2,510 to 2,547 against 2,509 to 2,543 M),ab.pymedian 109.78 → 109.94 ms. The probes past a home slot listed in a sixth run by a store and an add and run after the loop, with the per-token work in a closure that both loops call: the closure’s cursors stayed in memory, loaded and stored at every token, and branch misses rose 11.38 → 19.53 M; cycles 2,501 → 2,890 M.find_pastinlined, with the table behindblack_boxso that its address and size are read only on that path: instructions 4,875.6 → 4,923.9 M, cycles 2,538 → 2,544 M. -
After step 51, the probes’ buffer grown only when it is short (
if probes.len() < n + 32), instead ofresizeto the larger length at every block: instructions 4,875.3 → 4,870.6 M, cycles 2,538 → 2,539 M, for 2 more lines. -
After step 50, a token past 32 bytes keyed 0 by a conditional move (local, seed 1), instead of a branch to a key of 0xFF bytes: a length of 0 masks every byte off, and the key 0 probes to an empty slot, id 0. Instructions 4,949.7 → 4,944.9 M, but cycles 2,584 and 2,584 → 2,630 and 2,635 M (+1.8%): the walk’s token loop, one register short, then rebuilt the hash’s constant at every token.
-
The scanning threads’ tails mapping and unmapping nothing (on step 49). The tail’s wall time was 1.5 to 6 ms against 1.3 to 2.2 ms of CPU: each
munmapandmmapwaited on the memory-map lock while other threads dropped their 21 MB of corpus pages withMADV_DONTNEED. Releasing the window bits, check cells and first-match list byMADV_DONTNEEDinstead of freeing them, and reserving the grouping’satandidsbefore the walk, took T down 0.89 to 1.49 ms in six rounds of 41 (seeds 1 and 2), and 114.47 → 113.56 ms on seed 3. But with no lock waits the threads group at the same moment: memory.peak on seed 3 went 38.5 to 39.4 → 39.5 to 42.5 MiB, and 42.5 MiB is over B’s 44.0 MB cap before the board’s extra MB. For 12 lines, andscanpast clippy’s line limit, the net was about zero. Not kept. -
After step 48, the check cells dropped (local, seed 1). With the first matches halved, memory peaks as the threads group them, about 1.5 MB above the walks (in about half the runs, 33.0 against 34.6 MB), and the 326 KB of check cells per thread are freed by then. A check then added its match to its query’s cell, a random line of 400 KB, instead of its own cell beside its neighbours: 8 lines fewer, but cycles 2,712 and 2,649 → 2,830 and 2,793 M,
ab.py(41 alternating runs) median 117.24 → 120.90 ms, memory.peak median 35.0 → 32.4 MB over 5, about even at the board’s rates. With the query cell prefetched six checks ahead: cycles 2,705 and 2,709 → 2,741 and 2,735 M, medians 116.63 and 117.55 → 117.61 and 117.84 ms, memory.peak median 34.7 → 33.85 MB over 6, again about even. -
After step 45, glibc’s mmap threshold raised from 128 KiB to 512 KiB or 2 MiB, so that the tail’s frees and allocations reuse the arena instead of queueing on the address space’s lock (
ab.py, 21 alternating runs): medians 118.82 → 118.28 and 118.37 ms, but memory.peak over 5 runs, median 37.6 → 42.7 and 44.5 MB. -
After step 44, where the time goes at turbo off (local, seed 1, builds with timestamps, 12 runs, in ms since
main). The walks start at 10.5 to 12.7 ms and end over a spread of 2.2 to 4 ms (104.4 to 112.1 ms); in one run of twelve one thread ended 5 ms after the rest, which turbo on showed in half the runs (below). After its walk, a thread spends 0.35 to 0.95 ms dropping its pages, 0.5 to 0.8 ms on its last flush, 0.1 to 1.2 ms freeing its window, 0.15 to 1.25 ms merging its cells (the free included) and 1.2 to 3.1 ms grouping its 120,700 or so first matches, of which 0 to 1.1 ms is allocatingids, 0.1 to 1.2 ms allocatingat, 0.15 to 0.36 ms counting and 0.8 to 1.6 ms placing them, page faults onidsincluded: about 3.5 to 5 ms in all, whose spread is mostly the frees and allocations queueing on the address space’s lock. Formatting then takes 1.3 to 1.8 ms and the write 0.5 to 0.7 ms.perf recordwith the kernel’s samples: 5.3% of all cycles run in the kernel, two thirds of them in page faults, half of those on the corpus mapping. Not taken further: the work is the same on every thread, so only a dynamic handout of the corpus would win back the walks’ spread, about 1.3 ms above their mean. -
After step 44, the serial parts and the tail (local, seed 1, turbo on, so a run takes about 69 ms;
ab.py, 41 alternating runs, two rounds, medians, step 44 first). A build with timestamps (6 to 10 runs, ms sincemain): the plan is ready at 6.6 to 9.2, the walks end over a spread of 3 to 5 ms (62.0 to 68.7), and after its walk a thread spends 0.30 to 0.40 ms dropping its pages, 0.67 to 0.79 on its last flush and freeing its window (0.40 to 0.51 of it the frees), 0.25 to 0.48 merging its cells and 1.18 to 1.47 grouping its first matches; formatting takes 0.78 to 0.96 ms, spawns included, and the write 0.40 to 0.45. In 3 of its first 6 runs two scanning threads ended 15 to 28 ms after the others, as if they had shared a CPU. On CPUs 0, 2, 4, 6, 8 and 10 alone (6 threads, one per core) a run takes 77.18 ms against 70.42 on all 12. None of these paid:- Each parse thread starting a thread of its own that reads a byte per page of a twelfth of the corpus while the terms are interned: 71.23 and 69.87 → 71.28 and 69.63 ms.
- The last window flushed over the words its documents fill only (the flush 0.2 ms): 69.55 and 69.80 → 69.53 and 69.66 ms.
- Each scanning thread pinned to a CPU of its own (
sched_setaffinity): 69.78 and 70.13 → 69.96 and 70.01 ms (means 70.49 and 72.14 → 70.18 and 71.07). - The answers formatted by the scanning threads after a barrier, instead of new threads: 69.21 and 69.37 → 69.17 and 69.48 ms. With the two above: 69.34 and 69.38 → 69.07 and 69.14 ms, -0.35%, for about 20 more lines.
- Every parse thread interning its own terms into the shared table, claiming an empty slot by a compare-and-swap of its flags and taking ids from one atomic counter: interning 2.0 → 4.4 ms, as that counter’s cache line moves between cores at each new term, and the plan 0.6 ms slower with ids in no file order: 69.78 and 69.64 → 72.86 and 72.23 ms.
DENSE_SHARE16, 48, 64 and 128 instead of 32: 16 +3.0 ms and 128 +1.4 ms; 64 -0.14, -0.60 and -0.62 ms, but memory.peak median 40.1 → 42.0 MB over five runs; 48 -0.94, -0.66, -0.69 and -0.76 ms in four rounds (-1.1%), but 40.1 → 40.95 MB over ten (+2.1%), about even at the board’s exchange rates. With 48 for which queries run on sets and 32 for which terms keep a row, or the other way round: -0.11 ms each.WINDOW32 or 128: +0.26 and +0.09 ms; 32 withDENSE_SHARE48: -0.23 ms.SAMPLE_SHARE32 or 128: +0.68 and +0.10 ms.- A second prefetch per BOOL trigger, of the last byte of its checks, as a 40-byte check ends on the next cache line half the time: 69.30 and 69.11 → 70.02 and 69.83 ms.
- Without the drop of each chunk’s corpus pages (step 17): 68.77 → 70.37 ms, so it still pays.
The exit itself, from just before
exituntil the parent sees the process end, takes 1.14 ms (median of 15, min 0.92).
-
After step 43, the prefetch for BOOL triggers only (local, seed 1). The token loop prefetched the entry of a token with the BOOL flag and entry 0 otherwise, picked by
select_unpredictable: instructions 5,412.1 → 5,557.2 M, cycles 2,891 and 2,893 → 2,913 and 2,876 M against prefetching every token’s entry, for 2 more lines. -
After step 43, bounds on two other targets (local, seed 1,
perf stat -r 5). Skipping the loop that sets the rows’ bits saved 10 M cycles of 2,909, 0.35%; skipping the flushes of windowed bits,bit_index_sumamong them, saved 16 M, 0.55%. Neither was taken further. A probe that stops at a non-term token’s occupied home slot would need a bit set byintern; at +3 to 4 instructions per token against about 2.5 M fewer mispredicts it was not tried. -
After step 41, the line end as a call of its own (local, seed 1).
walkcalled its callback through a helper that is never inlined, so that the token loop would have the registers: instructions 5,796 → 6,538 M, cycles 3,172 → 3,345 M, as the line end then reads everything it captures through the closure, again after each store. -
After step 42, a write pointer instead of the token count (local, seed 1). The token loop bumped a pointer, and the count came from its offset after each block: instructions 5,382.2 → 5,358.7 M, cycles 2,992 → 3,018 M, and
ab.py, 41 alternating runs, two rounds, medians 129.04 and 131.86 against 129.11 and 127.90 ms, minimums 123.38 and 124.63 against 124.79 and 124.89 ms, for 2 more lines. -
After step 39, each token’s range of checks prefetched (local, seed 1). The BOOL triggers’ loop stalled on its load of
check_at[t], a 303 KB array read at random: 4.4% of all cycle samples sat on that load and the prefetches that wait for it. The line end’s token loop then prefetched it for each token. Picking the entry of a new BOOL trigger, or entry 0, by a conditional move, on step 38 with step 41’s fold: instructions 6,054 → 6,329 M and cycles 3,312 → 3,353 M, as the loop spilled registers. Prefetching every token’s entry: 6,147 M instructions and 3,247 M cycles there, but on step 41,ab.py, 41 alternating runs, median 131.77 against 131.65 ms without it, minimum 129.69 against 129.84 ms. -
After step 38, on the serial start (local, a build with timestamps, seed 1, medians of 10 runs, in ms since the process was spawned;
mainstarts at 2.0, as a trivial static binary’s does). The main thread alone spawns the parse threads (2.16 to 2.59), allocates the term table (0.94), interns the terms (3.02, 126 user instructions per occurrence at 4.3 per cycle), sums the sample (0.59), groups the phrases (0.26) and the checks (1.34), sets the stores (0.28), marks the table (0.73) and frees the planning’s lists (0.18): about 8.5 ms, against about 4.5 ms in which every thread works. Each scanning thread then takes 0.8 to 1.0 ms to set up before its walk begins at 15.2 to 15.7 ms. None of these changes paid:- The intern in a function of its own: 3.02 → 3.35 ms, and the pass about 4 ms slower in the same build, from the moved code.
- The terms’ keys touched before the intern, or prefetched 48 keys ahead: 3.05 ms.
- The term table zeroed by the kernel,
mmapandMADV_POPULATE_WRITE: 0.85 → 0.86 ms. - The table marked through the slot positions the intern recorded: 0.61 → 1.37 ms.
- The corpus faulted in ahead of the pass. With
MADV_POPULATE_READon the main thread: 9.1 ms, for a pass about 2 ms shorter. From helper threads, the intern waited about 10 ms on themmap_lock; per chunk in the scanning threads, 9 to 10 ms, serialized on the same lock. Helper threads reading a byte per page at nice 19: the parse, sample and plan about 2 ms slower, the pass about 1.6 ms faster, the wall 138.41 → 138.00 ms.
-
After step 33, on the serial parts (local, a build with timestamps, seed 1). The pass starts at 15.4 ms: parsing the queries takes 7.7 ms, of which interning 3.4, the sample 3.5, planning the queries 2.9 and marking the term table 1.1 ms. The threads’ passes run 129.5 to 131.6 ms. At its end, a thread spends 0.3 to 1.1 ms dropping its pages of the corpus, 0.5 to 0.75 ms on its last window flush, 0.3 to 1.25 ms freeing its sets, 0.2 to 0.9 ms merging its cells and 1.3 to 2.3 ms grouping its first matches. Formatting takes about 1.9 ms, the frees after it 1.3 ms and the write 0.5 ms. None of these changes paid:
- The intern loop’s prefetch 16 terms ahead (dropped at step 21) put back, or 8 or 32 ahead: interning took about 0.35 ms less, for 3 more lines.
- The queries, plan and chunks leaked instead of freed after formatting, as after step 17: three rounds of 20 runs, medians -0.96, +0.10 and -1.80 ms.
- Nothing freed at the end of a thread’s pass: median 152.28 → 152.27 ms, memory.peak 41.4 → 50.8 MB.
-
PGO (local, turbo off, on step 31’s code): a profile from three runs on each of full seeds 2 to 4, passed as
-C profile-use, with every function matching it.ab.py, 16 interleaved runs, medians / minimums: 161.21 / 157.44 → 168.09 / 160.76 ms and 158.09 / 155.53 → 161.43 / 159.20 ms on seed 1; 158.11 / 156.41 → 161.79 / 159.80 ms and 163.53 / 156.80 → 168.75 / 161.82 ms on seed 10, which it was not trained on.perf stat -r 5, twice: instructions:u 7.34 → 7.73 G, cycles:u 3.83 to 3.87 → 3.84 to 3.93 G, branch-misses:u 18.1 → 17.8 M. -
After step 17, on the serial start and the end (local, alternating runs, 16 each, against step 17 at 238.5 to 239.6 ms median). Where the time goes on seed 1: 2.1 ms from spawn to
main, parsing to 8.5 ms, the sample 5.3 ms, the per-query planning loop 5.2 ms and the rest of the plan 2.9 ms, so the pass starts at about 22 ms. The threads’ passes end over a 4 to 9 ms spread. After its pass, a thread spends 0.6 to 0.8 ms on its last window flush, 0.1 to 0.3 ms each on freeing the window and merging the check cells, and 1 to 2.7 ms grouping its first matches. Formatting takes 1.5 ms, joining the workers and freeing the chunks, plan and queries 1.3 to 1.4 ms, writing 0.6 ms, and the exit 0.8 ms. None of these changes paid:- The sample counted by all threads, one part each, then summed: the plan was ready 1.3 ms sooner (21.4 to 21.8 → 20.0 to 20.7 ms), but the wall did not move (239.6 → 240.1 and 238.5 → 239.1 ms), for 16 more lines (kept at step 20). The sample’s slots prefetched as in the pass instead (4 more lines) cut the sample from 5.3 to about 4.1 ms: 239.0 → 239.6 and 239.0 → 240.3 ms (kept at step 28).
- The queries, plan and chunks leaked instead of freed after formatting: the exit then took 1.7 to 1.9 ms instead of 0.7 to 1.0, and the wall went from 238.5 to 240.6 ms.
- The grouping’s two arrays written when allocated, as in step 16: 238.9 → 239.5 ms. Each
thread’s first-match list reserved at its bound (
SHOWN_IDSper query), so it never moves while it grows: 238.5 → 238.6 ms.
-
A static-pie build (
+crt-static, as tracks A and C use), on step 14 (local, turbo off):ab.py, 16 interleaved runs, median / min 246.00 / 245.60 ms against 245.75 / 244.05 ms. The dynamic loader’s quarter of a millisecond is lost in a 245 ms run. -
Transparent huge pages off on top of the fixed threshold (
prctl(PR_SET_THP_DISABLE)): 41.1 to 41.2 MB against 42.4 to 45.3 in the same session, but cycles 9.79 to 9.83 → 9.91 to 9.97 G and elapsed 0.383 to 0.385 → 0.392 to 0.397 s. Huge pages off without the fixed threshold gave 49.8 to 50.8 MB, andmalloc_trim(0)after planning 49.2 to 50.1 MB. -
Every BOOL query checked per document, with no sets at all (step 3 without the sets): 1.29 s, 29.0 G cycles, 53.3 MB, against 0.67 to 0.75 s and 14.0 to 14.2 G for step 2 in the same session. That meant about 100 million evaluations, each chasing a query’s heap-allocated terms and operators.
-
Step 3a’s two paths with per-term arrays instead of table slots: 15.1 G cycles, 0.64 s, 76 MB, against 13.2 G and 0.58 s for step 2. With 75,747 terms, every hit touched about six random cache lines: the 1 MB slot array, 2.4 MB of keys, the last-seen array, the store array, and two 1.8 MB arrays of
Vecheaders. Moving the flags into the slots fixed that. -
Term table grown at 3/4 load instead of 1/2 (2.1 MB of slots instead of 4.2): cycles 11.07 → 11.53 G, elapsed 0.535 → 0.55 s, memory 81 → 77.7 MB. The longer probe runs cost more than the smaller table saved.
-
One per-document loop shared by the sample and the pass, taking closures: fewer code lines, but cycles 10.0 → 10.6 G and instructions 12.25 → 13.60 G. A shared probe function that returned the slot cost 4% more cycles on its own. The pass keeps its loop inline.
-
A term table sized for every term occurrence up front instead of doubling: parse 13.8 to 14.7 → 10.7 to 11.0 ms, but 8.4 MB of slots instead of 4.2, as the queries hold 152,904 term occurrences and only 75,747 distinct terms.
-
Huge pages without the
reallocpath, every resize a new block and a copy: median wall 288.9 ms against 295.5 for step 6 (285.3 with it). The parse and the plan grow their arrays by copying. Withalloc_zeroedalso sent to glibc’scallocas well: 288.4 ms. -
Huge pages only for blocks of 4 MiB or more (the term table and its keys): the same cycles and memory as 2 MiB.
-
No branch per token at the line end, on top of step 6 (kept at step 25). A token that is no query term resolved to an empty slot with a reserved id and no flags, and the trigger lists grew by writing each entry and advancing by 0 or 1. Branch misses fell from 77.6 to 65.1 M, but instructions rose from 10.07 to 10.57 G and cycles stayed at 7.19 to 7.20 G. Prefetching the triggered checks after the token loop, or at first sight behind one branch, was 0.5 to 1% slower than step 6.
-
The full keys of long tokens prefetched in a pass between hashing and probing, on a variant of step 5 that was never merged: cycles 8.40 to 8.44 → 9.09 to 9.12 G, as the extra pass stalls on the slot loads it reads. On step 6, skipping the long-key comparison altogether (wrong answers, as an upper bound) saved only 1.5 to 2.8% of cycles, too little for a prefetch scheme to chase.
-
Phrase triggers pushed without a branch (each position pushed, then dropped again unless the term triggers phrases), on top of step 9: branch misses 68.8 → 67.2 M, but instructions 10.06 → 10.44 G and cycles 6.80 → 6.87 G.
-
Every BOOL query on sets, a window at a time, on step 25 (a prototype). Common terms keep their bitset rows; for the others the pass logs each document they occur in, and at each window’s end a counting sort groups the log by term into lists that every BOOL query is evaluated on, merging with galloping search. Correct on seeds 1 and 2;
ab.py, 12 runs each, two rounds: median 179.82 and 179.46 ms against 183.80 and 183.09 ms, about 2% faster, but memory.peak over four runs 52.1 to 53.9 MB against 41.9 to 43.0 MB. Of its 58.8 ms of BOOL work, logging took 11.5, grouping 8.3 and evaluation 39.0: at least 55 million merge steps, where the per-document checks run 16.9 million times. -
The query terms interned on every thread, after step 63 (local, turbo off). Eleven threads each parse a share of
queries.txtand intern their terms straight into one shared table: a new term claims its empty slot by a compare-and-swap of the slot’shead, takes its id from a block of 64 that its thread draws from an atomic counter, and publishes the id last (Release), which a probe that meets the sameheadwaits for (Acquire). The pass’s page-touching helper threads moved into the plan’s tail, two thirds of the threads. Gate 512 pass, 0 fail; 12 runs of seed 1 byte-identical (8 on 12 CPUs, 4 on 4).ab.py, 41 interleaved runs: seed 1 median 92.56 → 89.94 ms (min 91.58 → 88.79), seed 3 92.37 → 90.08 ms (min 91.15 → 89.12), about -2.6%. memory.peak, 3 alternating runs: 39.0 to 39.8 → 39.4 to 39.7 MB. But S 901 → 961 as pushed: K ×1.004, about +0.08 points, inside the local runs’ spread. As step 62 ran 7% slower on the board than here, it went to the board as a trial (step 64), to be kept only if its runs beat step 63’s 91.1 and 92.9 ms by more than their noise. Its run, run-bb4ed7d47695, read 93.4 ms, in a run where A, C and D read 1.5 to 3.4% above their best: no gain on the box against step 63, for 60 more lines. Reverted to step 63’s code, whose next run, run-79b6065fa154, read 98.1 ms in a slower run still (A 18.3, D 133.6 ms). Step 66 tried it again and kept it.
Track C: Join
Join a 200 MB CSV of records against a small region table and print one line of aggregates per country: record count, id sum, amount sum, min, max, distinct names, and the byte lengths of the names and notes after unescaping.
The CSV is hostile on purpose. Names and notes are quoted, "" stands for one ", a note can
hold a bare newline, records end in CRLF or LF, and a byte order mark can start any record. The
output still has to match the reference byte for byte.
| Reference | Mine | |
|---|---|---|
| Time, full dataset, seed 1 | 14.44 s | 19.3 ms |
| Peak memory | 367 MB | 11.3 MB |
| Code lines | 108 | 348 |
| Board points | 0 | 83.1 |
About 745 times the reference’s speed. The step I’d point you to in PERF.md is step 9, where sharding names by hash took the board time from 73.4 to 51.0 ms.
Approach
flowchart LR
R["regions.csv"] --> G["direct-address table<br/>one byte per region id"]
D["records.csv<br/>200 MB, mapped"] --> S["split at safe cut points<br/>no pass over the file first"]
G --> J
S --> J["12 workers, one run each<br/>AVX2 quote and comma masks"]
J --> N["names by hash owner<br/>128-bit letters in mailbox rounds"]
N --> M["per-thread sums<br/>merged in any order"]
M --> O["aggregates.txt"]
- The region lookup is a direct-address table. Countries are numbered in the order their first rows are read, and the table maps a region id to a group number in one byte. A missing id reads as group 0, the unmatched row, so the hot path has no comparison in it.
- The file is cut into one run per worker, and a cut can land inside a quoted note, where a newline is just data. So each run starts at the first newline after its cut that a digit or a byte order mark follows (spec §2.2), and nothing has to scan the file before the real pass.
- For each record, one AVX2 compare builds masks of the quotes and commas in the 64 bytes at the
name, and the ends of the name and the note come out of both masks at once, so a record is
walked field by field with no byte loop. A field’s unescaped length is its raw length minus
one per
""pair, which means no field is ever copied or rewritten and the parser never allocates a string. The id converts from one 8-byte word, and the region id and amount from one 16-byte vector, with no digit loop. - Each distinct name belongs to one thread, which keeps a hash table with 64 bits of the name’s hash and one bit per country. Threads trade 16-byte letters (a 128-bit hash plus the group) in rounds with a barrier between them. A table line never bounces between cores, and the only atomic left is one per thread per round, at the barrier, where the reference contends on every record.
- Codes are written bytewise, so the country order falls out of the table without a sort, and the per-thread integer sums merge in any order.
The input stays mapped, and what the program allocates is the name sets, the mailboxes and the region table.
Dependencies
None again.
cd track-c && cargo +1.99.1 build --release --offline
It’s a static, non-PIE executable like A and B (PERF.md, step 27). Static linking on its own skips the dynamic loader, which took about 0.25 ms of start-up.
With another 24 hours
What’s left is the probe loop and the barrier waits. Names and notes are hashed while still escaped, which is exact but reads every byte twice when a note is long, so a fast path for the usual unquoted, unescaped field would shorten the parse. Memory is 11.3 MB against a 7.3 MB cap, and the name sets and the mailbox pages are the two places where another megabyte would pay. Twelve workers are 7% faster locally but lose about 4 points on one board run in five when the box is busy; a cheap contention check inside the process that falls back to eleven workers would keep the speed without that tail risk.
Track C: performance log
Kept steps cite the board run that measured them. Local numbers come from my i7-13620H laptop with turbo off, comparing two versions side by side, and whatever I measured and dropped is listed under the step it followed.
| Reference (step 0) | Final code (step 54), three board runs | |
|---|---|---|
| T | 14.44 s | 19.34 ms (run-a66fe96b626a), 19.42 ms (run-dc3871163ade), 19.63 ms (run-a69fa3d057dc) |
| M | 367 MB | 11.3 MB, 11.4 MB, 11.6 MB |
| S (lines) | 108 | 348 |
| Points | 0 | 83.1, 83.1, 82.9 |
| Step | Change | Run ID | T (s) | M (MB) | Points |
|---|---|---|---|---|---|
| 0 | The reference, unchanged | 14.44 | 367 | 0 | |
| 1 | Rust v1: a quote-parity pre-pass splits the file for 12 threads, each runs a byte state machine, and one lock-free name table keeps a country bitset per name | run-7bddfb5dd3ec | 0.1204 | 39.3 | 57.4 |
| 2 | Each distinct name copied into one arena entry next to its country bitset | run-edd394160002 | 0.1133 | 39.0 | 58.0 |
| 3 | Transparent huge pages off | run-fbfe0ea92fbf | 0.1190 | 15.47 | 61.5 |
| 4 | Distinct names counted by the workers, from the atomic OR’s return value | run-e05eb5fa2929 | 0.1101 | 15.58 | 62.4 |
| 5 | regions.csv parsed in one pass, each row’s end found by the parse itself | run-e703239bd822 | 0.1016 | 15.31 | 63.2 |
| 6 | Names and notes scanned 32 bytes at a time for their next quote | run-599ba20d6eb1 | 0.0920 | 15.5 | 64.2 |
| 7 | Each name’s hash slot loaded as soon as the name is scanned, so its cache miss overlaps the rest of the record | run-7b03d961ed16 | 0.0799 | 15.3 | 65.7 |
| 8 | Numbers parsed from one 8-byte word each, and the number and text-field parsers inlined | run-c66327de718b | 0.0734 | 15.2 | 66.6 |
| 9 | Each distinct name owned by one thread: names travel to their owner in rounds, and each owner marks them in a private table. Region table at one byte per id | run-b8279a47babc | 0.0510 | 14.83 | 69.7 |
| 10 | Each run’s first record guessed instead of found by a quote pre-pass, with a check after the parse and an exact rerun when a guess is wrong. Each worker gives its input pages back after the last round | run-b480cbf26ce8 | 0.0418 | 14.8 | 71.7 |
| 11 | Hash slots tagged with 8 bits of the name’s hash, at half the size; regions.csv parsed on all threads; long names kept in the same table | run-cddb49a6dc40 | 0.0422 | 12.3 | 72.4 |
| 12 | The BOM test reads one byte before it compares three, which takes a bcmp call off every record. A sentinel record after the mapped input replaces step 10’s exact tail, and one thread replaces the quote pre-pass after a wrong guess | run-213d735f8f1d | 0.0368 | 12.2 | 74.3 |
| 13 | 18 fewer lines in the region table, the exchange and the name set, at the same speed | run-5fd07fa31be9 | 0.0415 | 13.0 | 72.8 |
| 14 | 11 fewer lines: one helper runs both thread groups, and the exchange wakes every worker | run-701b81269ca6 | 0.0368 | 12.4 | 74.3 |
| 15 | The input padded with 32 zero bytes after the sentinel record, so the field parsers lose their end-of-input paths and a per-record memcpy; 11 fewer lines | run-94c175e1147b | 0.0427 | 12.6 | 72.7 |
| 16 | Records parsed four at a time: each one’s byte in the region table prefetched as soon as its region id is parsed, and the four groups looked up after the fourth record | run-521d52addb7b | 0.0362 | 12.7 | 74.4 |
| 17 | A static-pie build, which skips the dynamic loader | run-521d52addb7b | 0.0362 | 12.7 | 74.4 |
| 18 | A leaner rewrite, 211 fewer lines at the same speed: run starts found exactly from spec §2.2, so the guessed starts, their check and rerun, and the sentinel record go | run-5cc15fc89abe | 0.0351 | 12.4 | 76.5 |
| 19 | 5 fewer lines with the same machine code: three pairs of variables set in one statement each, the regions header skipped in one line, and the cast lint exceptions in Cargo.toml | run-ad4d88cb83d7 | 0.0370 | 12.4 | 76.0 |
| 20 | 2 fewer lines with the same machine code: a worker’s position, run end and groups set in one statement, and so are a quoted field’s start and end | run-66de751504ed | 0.0389 | 13.0 | 75.3 |
| 21 | 3 fewer lines with the same machine code: one unsafe statement per mmap call, and the digit loop’s two updates in one assignment | run-af528e5f49cc | 0.0353 | 12.3 | 76.6 |
| 22 | 1 fewer line with the same machine code: the name set’s probe names the hash once and takes the slot and the tag from it | run-af528e5f49cc | 0.0353 | 12.3 | 76.6 |
| 23 | 17 fewer lines outside the record loop: each run’s pages given back in two lines, rounded out to whole pages; the region rows cut, marked and written in one line each; and the rounds counted and the parts merged in one line each | run-d4936b9f2b5b | 0.0349 | 12.7 | 76.7 |
| 24 | 1 fewer line: main maps both input files through one closure | run-b455f587cb61 | 0.0358 | 12.9 | 76.4 |
| 25 | A name’s letter masked to its length by a 24-byte window of a constant, and each letter posted at a running index into its owner’s mailbox | run-b89d1be25a5e | 0.0348 | 12.5 | 76.9 |
| 26 | The long-name compare out of line, so the probe for every other name stops paying for its bounds checks | run-8378d5c7581d | 0.0334 | 12.6 | 77.2 |
| 27 | A plain static executable instead of a static PIE (relocation-model=static) | run-a8bc41aa5aa0 | 0.0340 | 12.5 | 77.1 |
| 28 | A record’s name and note take their quotes from one 64-byte mask, built by AVX2 compares at the name’s start, where each quote cost a 32-byte scan | run-4dc3f93575f3 | 0.0319 | 12.5 | 77.7 |
| 29 | NameSet::read takes each letter with plain loads and its group as a byte, and insert is cold, so marking a name runs 17 fewer instructions per record | run-c02fb16de73f | 0.0312 | 12.5 | 77.8 |
| 30 | 5 fewer lines, three of them with the same machine code: the name set’s insert builds its entry in the push and its marking loop takes the group and the key in one statement, main writes the output in one line and reads each directory with nth, and merge sets the min and the max in one assignment | run-3ce10275f327 | 0.0310 | 12.2 | 78.1 |
| 31 | 1 fewer line with the same binary: the Dockerfile’s build stage mounts its sources instead of copying them | run-66c99a1d91aa | 0.0309 | 11.9 | 78.2 |
| 32 | The name set’s probe ends at its entry’s line, so a hit’s index is checked once, and the test for a long name moves into the cold compare | run-4ca7cce6e305 | 0.0303 | 11.9 | 78.4 |
| 33 | The join’s threads build the region table themselves, in two steps behind the round barrier, instead of on a pool of its own followed by two serial passes, with its pages mapped in on one CPU first; and the name sets are never freed | run-45ab2da93bdb | 0.0291 | 12.2 | 78.7 |
| 34 | The amount parses as one number in cents, every number finds its stop as its first byte below 0, the BOM test reads the id’s word, a letter’s stores read sent[to] once, the batch is made once per worker, and the input is prefetched 448 bytes ahead | run-91b80b654f7a | 0.0269 | 12.2 | 79.4 |
| 35 | The region id and the amount parse together in one SSE vector, the name and the note come from one mask of quotes and commas whose prefix XOR marks the quoted bytes, the name hash is CRC32, the name set’s key stays in one AVX2 register, and a letter’s slot is read unchecked | run-6252826712db | 0.0252 | 12.9 | 79.3 |
| 36 | The record batch holds each letter by reference, in an order whose loads are forwarded from their stores, and the group goes into its letter as one byte | run-5a15a73439c1 | 0.0246 | 12.5 | 79.7 |
| 37 | The merge takes its group from by_id without a bounds check, and a letter’s thread is picked with sent.len() instead of a load through the closure’s reference to the thread count | run-0ff0124ce494 | 0.0237 | 12.5 | 80.1 |
| 38 | The last worker to finish merges the groups, writes the output and ends the process while the others sleep, so no thread ends first, and each worker gives back its name set’s entries after its run; and main is C’s, so the Rust runtime’s setup, whose stack-overflow handler gave every thread a signal stack, does not run | run-490c7c238e52 | 0.0235 | 12.1 | 80.3 |
| 39 | The name’s 24 bytes, the region id’s and the amount’s 16 and the byte after the cents are read without bounds checks, a name set’s slot holds its entry above its tag, the quotes are counted with bzhi, a CR is told from an LF by its lowest bit, the region id’s length takes one compare, and the marking takes its group unchecked | run-d0d0e233e6f7 | 0.0228 | 12.5 | 80.5 |
| 40 | number reads a field’s word without a bounds check, as an unsafe fn whose six calls each show that the 8 bytes lie in the input or its pad, and the BOM test reads its byte unchecked | run-d1b2c0ca269e | 0.0240 | 12.2 | 80.1 |
| 41 | A name is known by a 128-bit hash of its bytes, three AES rounds: a letter is 16 bytes instead of 32 and is posted with one store, and a name set’s entry is 40 bytes instead of 64, 64 bits of the hash beside the name’s group bits | run-65f94ca68a16 | 0.0226 | 11.5 | 81.1 |
| 42 | 13 fewer lines at the same speed: region_amount and ALIGN written shorter, the cold paths without #[inline(never)], the mailboxes read in one for_each and published by their ends, and parallel written into join | run-d7d23764cf12 | 0.0219 | 11.4 | 81.6 |
| 43 | A waiter at the barrier sleeps in steps of 10 µs with 1 ns of timer slack, so a sleeper is no longer late for its next round, and rounds of 128 KiB, half as many barriers | run-f276c02c1223 | 0.0219 | 11.4 | 81.6 |
| 44 | 3 fewer lines at the same speed: the country numbers given by one for_each over present().zip(1..), with the count from present().count(), and the mailbox ends published in one for_each | run-42fe84676c85 | 0.0218 | 11.6 | 81.6 |
| 45 | The two hyperthreads of a core mark and parse side by side: a worker on an even CPU marks the round before’s letters before its parse and one on an odd CPU after it. The 64-byte window of text_fields and the name set’s probe read unchecked, and a new min or max is a branch instead of two stores per record | run-15ada601c130 | 0.0206 | 11.4 | 82.2 |
| 46 | NameSet::read leaves its loop at a new name, and insert calls it again from that letter, so the loop keeps the set’s slots, mask and entries in registers instead of loading them for every letter; and number parses on a 16-byte SSE window, with the shuffle and multiply-adds of region_amount | run-9d22ed670100 | 0.0208 | 11.6 | 82.0 |
| 47 | NameSet::read reads a name’s home slot and the next as one word and takes the next, with a cmov, when the home slot’s tag is not the name’s, so a name one slot past home no longer mispredicts; only names further on take the probe loop | run-ef37700846c7 | 0.0202 | 11.5 | 82.3 |
| 48 | The region table in one pass: a code’s group is the next number when its first row is read, given under a lock, so the second parse of the rows, its scans of the codes and one barrier go, and the output walks the codes in bytewise order to their groups | run-bb0b48a41b0b | 0.0217 | 11.3 | 81.6 |
| 49 | 23 fewer lines at the same speed: the region rows parsed in the worker, with their shares cut by the same closure as the runs; mallopt dropped, since no large buffer is freed any more; map_file panics with the path; the slow paths of number, text_fields and the rehash, values, prefix_xor and the output line written shorter | run-606261c589b8 | 0.0200 | 11.6 | 82.5 |
| 50 | Each worker’s 256 groups built on the heap, where Box::new built their 16 KiB on the stack first and the stack’s pages stayed mapped, and main runs worker 0 itself once it has started the others | run-606261c589b8 | 0.0200 | 11.6 | 82.5 |
| 51 | One worker fewer than the CPUs, so a CPU taken by another program leaves a spare one instead of halving a worker and every round | run-d27954c1c3a9 | 0.0217 | 10.7 | 82.0 |
| 52 | 8 fewer lines at the same speed: the Dockerfile’s build folded into one RUN, the imports in two lines, both prctl calls in one, BOM and SPINS written where they are used, two pairs of variables set in one statement each, and the name’s range returned straight from text_fields | run-486577623ea1 | 0.0212 | 10.5 | 82.4 |
| 53 | A worker on every CPU again, as in step 50: final scoring runs each batch with nothing else on the box, so step 51’s spare CPU only cost time | run-f9622a221638 | 0.0195 | 11.2 | 83.0 |
| 54 | 9 fewer lines at the same speed: the name set’s probe tests a hit in one closure and takes its tag and group as bytes of the hash, a long name is told by a let-else, the slow quote scan carries its parity into bit 0, the name’s quote counts are not named, the group’s byte is written through its word, the mailboxes are leaked, and main reads the data directory where it maps the files | run-dc3871163ade | 0.0194 | 11.4 | 83.1 |
Local numbers are for full seed 1. “P-cores” means CPUs 0 to 11 with all 12 threads and turbo off, which matches the box within about 7%. “E-cores” means CPUs 12 to 15. They have no hyperthreads, so they overstate any change that hides memory stalls (see the batching experiment below).
Step 1: v1
The file is cut into 12 chunks. A parallel pre-pass takes the parity of each chunk’s quote bytes, and a prefix XOR over the parities tells each cut whether it sits inside a quoted note, so every thread finds its first record without parsing the chunks before it. Each thread then walks its records byte by byte, looks up the region in an array indexed by region id, and sums into its own per-country totals. Distinct names go through one lock-free hash table shared by all threads, with one bit per country for each name.
Locally on P-cores: 135 ms wall, 1.18 s user CPU. On E-cores: 0.416 s, 2.56 G cycles.
Step 2: name-table entries in one arena
Each distinct name’s bytes are copied once into a shared arena entry that also holds its per-country bitset. Before, a record compared its name against the name’s first occurrence in the 200 MB file, a near-certain DRAM miss, then read a separate span table and bitset. Now a record touches only its hash slot and one entry, where the compare and the atomic OR share a cache line.
- E-cores,
perf stat -r 5: cycles:u 2.56 → 1.97 G, task-clock 1475 → 1145 ms, elapsed 0.416 → 0.326 s, instructions:u 2.54 → 2.66 G. S 397 → 412. - P-cores: about 15% less wall time.
- Board: 113.3, 118.5 and 119.1 ms over three runs of this code, against 120.4 ms for v1. A single board run varies by about ±3%.
Step 3: transparent huge pages off
The name table’s arena grows at one front that all 12 threads write. With THP set to “always”,
every thread that faults on a fresh 2 MB region of it before the first fault finishes gets a
2 MB page of its own: the kernel allocates, charges and zeroes the page before it takes the
page-table lock and finds the region already mapped. The losers free their pages, but memory.peak
has already counted them. prctl(PR_SET_THP_DISABLE) at startup makes every fault a 4 KB one.
THP is “always” on this machine, and the board’s 39.3 MB for step 1 is the local peak with THP on
(37.5 MiB), so the box is likely the same. To find the extra memory, an instrumented copy read the
cgroup’s memory.current and memory.stat at each phase boundary on P-cores. When the workers
finished, memory.current was 14.8 MiB (anon 12.7, 6.0 of it huge pages), yet memory.peak was
37.1 to 37.8 MiB, so 22 MiB existed only for moments inside the worker phase. /proc/self/smaps put
the 6 MB of huge pages in the mapping that holds the slots and the arena. On 4 E-cores at most 4
threads fault at once, so the peak there is only about 18 MiB, which is why the first measurements
missed it.
P-cores, three interleaved rounds:
| step 2 | step 3 | |
|---|---|---|
| memory.peak, user scope (MiB) | 37.5 / 37.5 / 37.9 | 15.3 / 15.6 / 15.1 |
| memory.peak, container with the harness’s flags (MiB) | 38.0 / 37.3 / 37.9 | 14.7 / 15.0 / 14.7 |
task-clock, perf stat -r 10 (ms) | 1186 / 1172 / 1158 | 1202 / 1186 / 1202 |
| elapsed (ms) | 123.3 / 122.0 / 124.4 | 124.7 / 122.8 / 124.5 |
The board measured 15.47 MB, down from 39.0 MB. The 4 KB pages cost about 2% more CPU time and 0.6% more wall time. S 412 → 415.
What remains, from the same instrumented copy with THP off: 4.0 MiB of hash slots, 5.2 MiB of arena in use (of 18 MiB reserved) and 1.9 MiB of region array, 11.4 MiB of anonymous memory in all. In the container the highest sample was 11.5 MiB anon plus 1.1 MiB of kernel memory, 0.6 MiB of it page tables for the 200 MB input mapping.
Step 4: distinct names counted by the workers
The distinct-name counts used to come from a walk over every arena entry after the workers had joined, 9 ms on one thread. Now the atomic OR that sets a name’s country bit returns the word it replaced, so the one record that sees the bit go from 0 to 1, in whichever thread, counts the name for its country. Each bit flips exactly once, so the per-thread counts always sum to the same totals, and the walk is gone.
P-cores, perf stat -r 10, three interleaved rounds:
| step 3 | step 4 | |
|---|---|---|
| task-clock (ms) | 1200 / 1198 / 1198 | 1139 / 1147 / 1169 |
| elapsed (ms) | 123.9 / 124.0 / 124.0 | 111.5 / 113.1 / 114.2 |
On the board this code measured 110.1 ms in run-e05eb5fa2929 and 111.3 ms in run-a133933027d0.
S 415 → 402, and memory.peak is unchanged at 14.8 to 15.4 MiB. Because the old value is now used,
the OR compiles to a lock cmpxchg loop instead of lock or. LLVM can emit lock bts for this
pattern, but only if the optimizer has not already rewritten the bit test, which it had here. The
loop did not show in task-clock.
Step 5: regions parsed in one pass
Profiled alone on a P-core, the old parse of regions.csv (200k rows, 2.2 MB) took 10.1 to 10.5 ms,
all before any other thread starts. It made two passes, and each one split the rows at LF
(1.4 to 1.6 ms) and then parsed each row (3.5 to 4 ms), with a search for the comma, a validation loop
per field and a fold per field.
Region ids ascend (spec §2.3), so the last row’s id now sizes the array up front and one pass is
enough. That pass stores each region’s country code and marks the countries present, and once the
countries are numbered, one walk over the array swaps each code for its group. A row parses as
digits up to the comma, followed by a fixed ,XYZ and LF that one slice pattern checks, so the
row’s end comes out of the parse without a separate search. Alone, the new parse takes 2.9 to 3.1 ms:
2.5 to 2.7 ms for the rows, 0.5 to 0.6 ms for the walk over the 1M-entry array and 0.03 ms to number the
countries.
P-cores, perf stat -r 10, three interleaved rounds:
| step 4 | step 5 | |
|---|---|---|
| task-clock (ms) | 1144 / 1149 / 1164 | 1144 / 1150 / 1145 |
| elapsed (ms) | 116.8 / 113.1 / 114.1 | 105.6 / 106.7 / 108.3 |
S 402 → 416, and memory.peak is unchanged at 15.0 to 15.1 MiB. The parse is now stricter outside the spec: a blank line, a last row without its LF, or an id larger than the last row’s returns an error, where the old parse accepted them.
Step 6: quoted fields scanned 32 bytes at a time
perf record on P-cores put 76% of the samples in the worker loop, which has the name table
inlined into it, 17% in text_field, 4.6% in the quote pre-pass and 0.2% in the regions parse.
Knockouts of step 5 then split the worker loop (P-cores, perf stat, each knockout beside its
baseline in the same session):
- Without the name table a run takes 557 ms of task-clock and 58 to 59 ms elapsed, against 1129 to 1142 ms and 106 to 118 ms. Without the region lookup as well, 553 ms and 56 to 57 ms. The scan is half the time, the name table the other half, and the region lookup about 2%.
- Hashing each name and loading its slot costs 0.1 G cycles: 1.39 G against 1.29 G for the scan alone. Finding the arena entry, comparing the name and setting the bit cost 0.92 G more when the slot is loaded right after the name. The entry adds 2.7 L2 misses per record and 3.8 M page walks, which are active in 7% of all cycles, since the arena has had 4 KB pages since step 3.
- The atomic OR costs 7% of task-clock: 1059 to 1089 ms when the bitset word is only read, against 1146 to 1166 ms with the OR. It also moves lines between cores: 1.37 M loads are served from another core’s cache, against 0.28 M without it. Testing the bit before the OR (1172 to 1199 ms) saves nothing, because 90% of records set a new bit.
Names and notes are 37 of a record’s 60 bytes on average, and the old text_field stepped
through them one byte at a time, with a compare and a branch per byte. Inside a quoted field only
the quotes matter, so text_field now compares 32 bytes with " at once and jumps to the first
match, the lowest set bit of the 32-bit mask. A name or a note usually ends within the first
step. The mask is built by a plain loop over a [u8; 32], which compiles to one vpcmpeqb and
one vpmovmskb, so the scan needs no unsafe and no intrinsics. Instructions fall from 2.585 G
to 2.035 G.
P-cores, perf stat -r 10, three interleaved rounds:
| step 5 | step 6 | |
|---|---|---|
| task-clock (ms) | 1152 / 1143 / 1136 | 1021 / 1002 / 985 |
| cycles:u (G) | 2.58 / 2.55 / 2.54 | 2.27 / 2.22 / 2.17 |
| elapsed (ms) | 110.6 / 105.6 / 108.9 | 94.7 / 95.2 / 93.1 |
S 416 → 426, and memory.peak is unchanged, 14.7 to 15.0 MiB. On the board this code measured 92.0 ms in run-599ba20d6eb1, at commit 2f88e04, which carries the same track C code.
Step 7: each name’s slot loaded as soon as the name is scanned
Step 6’s knockouts found that hashing a name and loading its slot cost only 0.1 G cycles when
the slot load sat right after the name. In step 6 it sat at the end of the record, inside
mark, after the note and the numbers, so each record stalled on the slot’s cache miss with
nothing left to parse. Now NameTable::probe hashes the name and loads its home slot as soon as
text_field returns the name, and mark takes the hash and the slot’s value at the end of the
record. The note and the three numbers parse while the miss is pending.
The early value can only be out of date in one way. A slot that holds a name never changes, and
an empty slot that another thread fills in between makes intern lose the race to publish, a
case it already handled. A full run still interns about 100.53 k names and wastes at most about
15 entries more than before. A build whose probe always reports an empty slot, which sends every
record down that path, passes the gate and 400 random cases against the reference.
P-cores, perf stat -r 10, three interleaved rounds:
| step 6 | step 7 | |
|---|---|---|
| task-clock (ms) | 1005 / 1032 / 1017 | 912 / 933 / 926 |
| cycles:u (G) | 2.22 / 2.29 / 2.25 | 2.00 / 2.05 / 2.03 |
| elapsed (ms) | 97.8 / 99.2 / 99.7 | 89.6 / 91.1 / 87.4 |
Instructions barely move, 2.035 → 2.046 G. S 426 → 432, and memory.peak in the container with the harness’s flags is unchanged, 14.8 to 15.0 MiB. On the board this code measured 79.9 ms in run-7b03d961ed16, at commit ce4de64, which carries the same track C code. The board skipped b9cb846 itself when a newer push replaced it in its queue.
Step 8: numbers parsed from one word, and the field parsers inlined
A line-level profile of step 7 (P-cores, perf record) still puts most of the worker loop in the
name table. On the parsing side, the loops over number digits held about 10% of the samples, and
3.1% sat right after a 16-byte load that read back part of text_field’s result from the
stack. Branch misses ran at 2.7 per record, 9.06 M in all. Three changes followed, each measured
on top of the one before (P-cores, three interleaved rounds):
numberparses a field whose stop byte lies within 8 bytes from one little-endian word. XOR with the stop byte in every byte makes each stop a zero byte, and the zero-byte test finds the first one. Shifting the digits to the top of the word turns the missing ones into leading zeros, and three multiplies join digits into pairs, pairs into fours and fours into the value. There is no loop and no branch on the field’s length. Longer fields, which §2.1 allows with leading zeros, and the file’s last 7 bytes keep the byte loop. Measured withperf stat -r 10: task-clock 916 / 899 / 911 → 859 / 864 / 871 ms, cycles:u 2.01 / 1.97 / 2.00 → 1.87 / 1.89 / 1.91 G, instructions 2.046 → 1.872 G, and branch misses 9.06 → 5.03 M.text_fieldis always inlined. As a call it returned four words through the stack, and the caller read two of them back with one 16-byte load. Store forwarding cannot merge two 8-byte stores into one load, so that load waited until both stores reached the cache. Measured withperf stat -r 10: task-clock 876 / 883 / 868 → 841 / 840 / 842 ms, cycles:u 1.92 / 1.94 / 1.90 → 1.84 / 1.83 / 1.84 G, and instructions 1.872 → 1.769 G.numberis always inlined too. At each call sitestopis a constant, so the call and the multiply that copiesstopinto every byte disappear, 29 instructions per record. Measured withperf stat -r 30: task-clock 844 / 839 / 845 → 824 / 812 / 824 ms, elapsed 80.7 / 79.6 / 81.5 → 78.6 / 78.3 / 82.3 ms, and instructions 1.769 → 1.673 G.
A plain #[inline] left text_field a call, so both use #[inline(always)]. number was
checked against the byte loop on 200,040 fields: every length from 0 to 20 digits, both stops,
random bytes after the stop, and 20-digit values that wrap.
Step 7 → step 8 on P-cores, three interleaved rounds:
| step 7 | step 8 | |
|---|---|---|
task-clock, perf stat -r 30 (ms) | 901 / 911 / 907 | 830 / 824 / 828 |
elapsed, perf stat -r 30 (ms) | 87.5 / 89.0 / 87.8 | 78.8 / 78.5 / 79.4 |
cycles:u, perf stat -r 10 (G) | 2.05 / 1.98 / 2.03 | 1.82 / 1.81 / 1.80 |
| instructions:u (G) | 2.046 | 1.673 |
| branch misses (M) | 9.06 | 5.10 |
S 432 → 447: 13 lines for the word parse and 2 for the attributes. memory.peak in the container with the harness’s flags is unchanged, 14.7 to 14.8 MiB against 14.8 to 15.2 MiB for step 7.
Step 9: each distinct name owned by one thread
Steps 2 to 7 tuned one name table that all threads shared, and it still cost about half the
time. With all name hashing, posting and marking knocked out of the prototype below, the rest ran
in 42.6 ms (local, median of 11), against 85 to 88 ms for step 7 in the sessions around it. In
step 7 each record’s lookup missed the cache on a line that other cores also wrote, and set its
bit with a lock cmpxchg loop.
Now each name has one owner thread, picked by its hash, and only the owner touches the name’s entry. The workers run in rounds. In each round a worker parses 64 KiB of its chunk and posts each record’s name and group to the owner’s mailbox as a 32-byte letter, and then all workers meet at a barrier. After it, each worker marks the letters posted to it in its own hash table.
- A name of up to 24 bytes travels inside its letter, zero-padded, with its hash and length in
the fourth word, so the owner compares 32-byte keys and never reads the file. Longer names
travel as offsets into the file and go to a
HashMap. They are rare: 203 of seed 1’s 3.32 M records. - An entry is one 64-byte line: the 4-word key, then the 241-bit country bitset. The compare and the bit share the line, and the bit is set with a plain OR.
- The mailboxes come in two sets that alternate by round, so one barrier per round separates posting from reading. A waiting worker spins 2000 times and then parks, and the last worker to arrive unparks the others.
- The region table holds one byte per id, 1 MB instead of 2 MB. Groups past 254, which the grammar allows and the generator never writes, read as 255 and are looked up in a sorted side list.
mallopt(M_MMAP_THRESHOLD, 64 KiB)runs at startup, and each table reserves room for twice its expected names (pages that are never written are never charged). A build without either peaked at 19.8 to 20.2 MiB. Freeing the regions parse’s 2 MB scratch array had raised glibc’s dynamic mmap threshold to 2 MB, so the tables came from malloc arenas and grew there by copying, and the old copies stayed resident.
The prototype was built on step 7, before step 8 existed, in stages (local, P-cores, medians of 15 interleaved runs against the build before it unless noted):
- Names sent as offsets into the file and compared there, with a barrier that only spins: 69.6 ms against 88.0 ms for step 7, but with runs of 161 and 171 ms. When the scheduler delays one worker, the other eleven keep their CPUs busy spinning.
- A barrier that yields instead: 69.8 against 85.0 ms, with runs of 90, 129 and 147 ms.
- Spinning 2000 times and then parking: 70.2 against 86.1 ms, worst run 77 ms. Kept.
- Names of up to 24 bytes inside the letter, and entries of one cache line: 64.2 against 70.3 ms.
- The marking loop kept out of line (63.4 against 64.0 ms, 11 runs), then the byte-wide
region table,
malloptand the doubled reserve: 59.4 against 63.9 ms.
Knockouts of stage 3 (medians of 11, one session): 71.5 ms in full, 51.6 ms with the letters
posted and read but no name marked, and 42.6 ms with no name hashed, posted or marked (the rounds
and barriers stay). So marking cost about
20 ms and the exchange about 9 ms, and stage 4 went after the marking. perf stat -r 5:
| step 7 | stage 3 | stage 4 | no name work | |
|---|---|---|---|---|
| task-clock (ms) | 891 | 727 | 620 | 390 |
| cycles:u (G) | 1.949 | 1.669 | 1.403 | 0.890 |
| instructions:u (G) | 2.046 | 2.257 | 2.094 | 1.379 |
| branch misses (M) | 9.06 | 12.75 | 6.21 | 5.68 |
| loads that missed L2 (M) | 12.1 | 9.08 | 6.44 | 2.89 |
| elapsed (ms) | 87.7 | 71.8 | 64.2 | 42.6 |
Phases of stage 4, from an instrumented copy that logged timestamps per thread: each worker spends 31.5 to 32.1 ms parsing and posting, 4.5 to 5.5 ms waiting at 257 barriers (parking 18 to 21 times), and 10.2 to 11.0 ms marking. A wait takes 4 to 6 µs at the median, 13 to 21 µs at p90 and 330 to 380 µs at p99. Of the marking, reading the letters takes 2.44 ms per worker and finding their slots 0.09 ms more (2.53 ms in all), against 10.79 ms in full. The entries cost 69 instructions, 87 cycles and 1.01 L2 misses per letter on top of reading it.
Step 9 is that prototype on top of step 8. P-cores, three interleaved rounds:
| step 8 | step 9 | |
|---|---|---|
task-clock, perf stat -r 10 (ms) | 837 / 841 / 829 | 498 / 498 / 497 |
elapsed, perf stat -r 10 (ms) | 81.6 / 79.2 / 81.9 | 52.3 / 52.3 / 51.7 |
| cycles:u (G) | 1.83 / 1.84 / 1.80 | 1.12 / 1.12 / 1.12 |
| instructions:u (G) | 1.673 | 1.659 |
| branch misses (M) | 5.09 | 2.90 |
| memory.peak, user scope (MiB) | 14.42 / 14.56 / 14.29 / 14.76 | 13.90 / 13.77 / 14.18 / 13.96 |
Over 21 interleaved runs, the wall-time medians are 80.71 ms for step 8 (min 75.40) and 52.77 ms
for step 9 (min 51.65), with the stage-5 prototype on step 7 at 59.54 ms in the same session.
With the private tables, THP no longer changes the peak: 13.80 to 14.18 MiB with the prctl and
13.76 to 14.28 MiB without it (4 runs each), so the call stays only as insurance. S 447 → 587.
Correctness checks: the gate (307 pass, 0 fail); fresh seeds 5 to 7; full seeds 2 and 3 at 1 and
64 threads; and the 400 random cases plus two long-name sets against the reference, at 1, 3,
12, 37 and 64 threads, and again with 100-byte rounds and 3-letter mailboxes at 1, 2, 3, 12
and 64 threads, which forces thousands of rounds and early round ends. The long-name sets hold
every name length from 0 to 80 bytes, names equal in their first 24 bytes, trailing-space
twins, "" escapes at the 8-byte word edges, and quoted and unquoted spellings of one value.
Step 10: guessed run starts, and the input released by the workers
This step goes after the time outside the worker loop. A timeline of step 8 (P-cores, an
instrumented copy) put the regions parse at 3.1 to 3.3 ms, the quote pre-pass at 6.4 to 6.7 ms, the
workers at 62 to 68 ms, the merge at 0.7 to 1.0 ms and the write at 0.05 ms. When the process
exits, the kernel unmaps the 200 MB input on one thread: an explicit munmap took 2.8 ms, and
the time from the program’s last timestamp to the end of the wall was 4.5 to 5.1 ms (medians of
40 runs, two sessions).
-
Each worker releases its own run. After the last round, every worker calls
madvise(MADV_DONTNEED)on the whole pages of its run, so the unmapping runs on twelve threads instead of one at exit. It waits for the last round because dropping pages makes the kernel flush every thread’s TLB, which slows any worker still parsing. On step 8, the gap after the last timestamp fell from 4.51 and 5.08 ms to 2.03 and 2.70 ms (medians of 40 runs, two sessions). Releasing without waiting for the other workers was slower there:perf stat -r 30elapsed 80.3 / 81.9 / 80.0 ms, against 79.6 / 77.8 / 79.3 ms after a barrier. Step 9’s rounds already end at a barrier, so the release needs none of its own. -
Run starts are guessed. Instead of the pre-pass, each cut takes the first LF after it that a digit or a BOM follows. A record starts that way, and §2.2 says a note’s LF is always followed by a lowercase word or a quote, so on generated data no guess is wrong. §2.1 allows any byte there, so the guesses are checked: each worker returns where the parse of its run stopped, and every run must end exactly where the next one starts. Otherwise the join runs again on the pre-pass’s exact cuts, with a fresh exchange. The parse is exact from the file’s start, so if each run ends on the next one’s start, by induction every start is a record start.
A wrong guess must cost time, never a crash, and a misread record can read past its run. Every scan in a record stops at a comma, a dot or an odd run of quotes, and a quoted field that holds more than quotes opens and closes with an odd run. So a misread record never reads past the first real record whose name and note are such fields. The file’s tail, from the first record start in its last 4 KiB, has an exact start: a valid file holds an even number of quotes, so the parity of the quotes in the last 4 KiB is the quote state where they begin. The tail must hold such a record, which takes a few records’ parse to find, or the join uses the pre-pass. The guessed runs all end at the tail’s start, and the last worker parses the tail after its run, from that exact start. A separate thread for the tail would have shared a CPU with a worker and waited at all of the ~257 barriers.
Both on top of step 9, P-cores, wall time of interleaved runs (ab.py), median and min in ms:
| step 9 | release only | guesses only | both | |
|---|---|---|---|---|
| session 1, 60 runs each | 52.68 / 51.09 | 51.30 / 49.99 | 47.69 / 46.74 | 46.43 / 45.50 |
| session 2, 60 runs each, order reversed | 53.61 / 51.49 | 52.25 / 49.96 | 48.88 / 46.51 | 47.81 / 45.48 |
| session 3, 60 runs each | 54.04 / 51.19 | 47.88 / 45.73 |
The release saves 1.1 to 1.5 ms and the guesses 4.4 to 5.0 ms; together 5.5 to 6.3 ms. In the quietest
perf stat -r 10 round, task-clock was 501.4 ms for step 9, 511.3 with the release, 490.4 with
the guesses and 501.6 with both. Page faults stay at 6,675: the workers now fault the input in
as they parse it.
memory.peak in the container with the harness’s flags and 12 CPUs, 12 alternating runs each: 13.3 to 14.3 MiB (mean 13.99) for step 9 and 13.9 to 14.6 MiB (mean 14.16) for step 10. S 587 → 630: 10 lines for the release and 33 for the guesses, their check and the tail.
Correctness checks:
- The gate (307 pass, 0 fail). Every guess held on all 300 tiny seeds at 1, 3, 12, 37 and 64 threads, and on full seeds 1 to 7 at 1, 12 and 64 threads.
- The 400 random cases, and 400 hostile ones against the reference at 1, 3, 12 and 64 threads with 64-, 200- and 1,000-byte tails. The hostile cases put into names and notes what §2.1 allows and §2.2 rules out: LFs followed by digits or BOMs, whole fake records, CRLFs, dots and stray quotes. Up to 332 of the 400 runs guessed wrong, and all reran to the reference’s output.
- A forced test on every byte offset of 7 tiny seeds, the worked example, 4 random cases and 60 hostile ones, with 64-, 1,024- and 4,096-byte tails: 648,626 exact cuts gave the same output and ended where the next run starts, and 498,540 offsets forced as guesses never crashed, were accepted exactly when they were record starts, and then gave the same output.
Step 11: tagged hash slots, and regions parsed on all threads
- Tagged slots. Each u32 slot of a worker’s name table holds its entry’s index plus one in the low 24 bits and 8 bits of the name’s hash in the top 8. A probe that meets another name’s slot sees the tag differ and moves on without loading that name’s entry line. With the tags the table halves to 16k slots per worker, sized at 4/3 of the names it will hold and grown at 3/4 load. Halving the slots without tags cost 3% of T; with them T fell 4.8%.
regions.csvparsed on all threads, one even share of the rows each, into row lists sized up front. The serial parse and the walk over the 1M-entry id array took 3.8 ms before the join could start; the parallel parse takes about 2.5 ms. Without the sizing, glibc’s per-thread arenas gave 1.5 MiB of the saving back.- Fewer lines. Names over 24 bytes go into the same tagged table. Their key is a pair of
file offsets, compared in the file only when the hashes match, so the separate
HashMapgoes. Groups wider than 254 countries use aHashMapinstead of a sorted list. Region ids no longer need to ascend: the reference accepts them in any order, and step 10 stopped with an error on them.
On top of step 10, P-cores, wall time of interleaved runs (ab.py), median / min in ms:
| step 10 | step 11 | |
|---|---|---|
| session 1, 41 runs each, load average 18 | 47.96 / 45.70 | 44.16 / 42.08 |
| session 2, quieter | 46.44 / 45.60 | 43.17 / 42.58 |
memory.peak in the container with the harness’s flags, 8 runs each: median 13.84 MiB (13.35 to 14.01) for step 10 and 12.39 MiB (11.78 to 12.73) for step 11. S 630 → 622.
Correctness checks: the gate (307 pass, 0 fail); the 402 random cases at the default thread count and at 1, 3, 12, 37 and 64 threads; tiny rounds (100-byte rounds, 3-letter mailboxes) at 1, 2, 3, 12 and 64 threads; and against the reference, at the default count and at 64 threads, a region set with groups wider than 254 countries and one with shuffled ids. A bad region row still stops the join with its error.
Step 12: one bcmp call less per record, and 59 lines less
- The BOM test.
data[at..].starts_with(BOM)compiled to a call to glibc’sbcmpfor every record, after avzeroupper, because LLVM left the 3-byte compare as a call. Testing the first byte first leaves the call to the records that start with 0xEF. - A sentinel record instead of the exact tail.
map_filemapsrecords.csvover a reservation of anonymous memory and writes one more record after it,0,"a","a",0,0.00on a line of its own. Its name and note are quoted, so a parse from a wrong guess stops within it at the latest, as step 10 showed for any such record. Step 10’s tail is then redundant: no quote parity over the last 4 KiB, no search there for such a record, no jump of the last worker into the tail, and nonext_record_start. The last run ends at the end of the file. The mapping is writable and private; writing the sentinel copies at most the file’s last page, and no run’s pages hold it, so the release never drops it. - One thread instead of the pre-pass after a wrong guess. Guesses go wrong only on files
outside §2.2, where speed is not scored, so the rerun parses the whole body on one worker
from its exact start, and
record_boundsand its parallel quote count go. - Smaller cuts.
Group::EMPTYreplaces theDefaultimpl, and the output walk zips the keys with the groups.
On top of step 11, P-cores, wall time of interleaved runs (ab.py, 101 runs each), median / min
in ms. “Lines only” is items 2 to 4 without item 1.
| step 11 | lines only | step 12 | |
|---|---|---|---|
| session 1 | 43.17 / 41.87 | 43.36 / 41.91 | 40.47 / 39.71 |
| session 2 | 43.09 / 41.83 | 40.57 / 39.68 |
memory.peak in the container with the harness’s flags, 6 runs each: 12.7 to 13.3 MB for step 11
and 12.5 to 13.5 MB for step 12. Page faults stay at 6,390. S 622 → 563: the pre-pass -23 lines,
the tail -27 (-40 there, +13 for the mapping and its constants), Group::EMPTY -4, the output
walk -5.
Correctness checks: the gate (307 pass, 0 fail); full seeds 1 to 4 against the reference; the 400 random and 400 hostile cases at the default thread count and at 1, 3, 12, 37 and 64 threads, where up to 397 of the hostile runs guessed wrong and all reran to the reference’s output; and every byte offset of the body of 72 files (490,079 offsets), each forced as an exact cut and as a guess with the second run reading on into the sentinel: no crash or hang, and the 8,783 offsets that are record starts tiled and gave the same output.
Step 13: 18 fewer lines
Line cuts in the region table, the exchange and the name set, checked against the machine code:
the parse loop compiles to the same instructions as step 12’s; only the barrier’s spin loop and
the order of one bit test in NameSet::read changed. Three cuts that changed the hot loop’s
code were put back: each cost 0.15 to 0.3 ms. ab.py, 50 interleaved runs, median / min: step 12
40.51 / 39.68 ms, step 13 40.77 / 39.62 ms. memory.peak, 6 runs: 11.68 MiB median, within the
±0.8 MiB of the per-CPU charge batching. S 563 → 545. Gate: 307 pass, 0 fail; the 402 random
cases at 1, 3, 12, 37 and 64 threads and in the tiny-round build; the output hash is unchanged.
Step 14: 11 fewer lines
A 6-line parallel(n, &work) helper replaces the two thread::scope spawn and join blocks, in
the regions parse and the join. Exchange::wait now unparks every worker, itself included,
which is harmless and drops its me parameter. The record loop is 585 instructions in both
builds; the only difference in the hot code is the instruction order inside the hash of
wide[&id], which runs only for a region group of 255 or more, and 240 countries never get
there. Dropped: removing the barrier leader’s early return, which saved a line but changed the
hot loop’s register allocation.
ab.py against step 13, median / min: full runs (60 each) 40.44 / 39.73 → 40.34 / 39.58 ms;
regions only (100 each) 4.73 / 4.24 → 4.81 / 4.16 ms. memory.peak, 4 runs: 12.23 → 12.22 MiB.
S 545 → 534. Gate: 307 pass, 0 fail; the 402 random cases at 1, 3, 12, 37 and 64 threads and in
the tiny-round build; the output hash is unchanged.
Step 15: a padded input, and no memcpy per record
The board’s first run of this code, run-46d1884323c7, drew 54.9 ms while A, B and D ran at their usual times; the next run of the same code, run-94c175e1147b, took 42.7 ms: that is the row. Every worker waits at each round’s barrier, so one interrupted thread delays them all.
The sentinel record after the file is now followed by 32 zero bytes. Every position a parse
reaches lies before those zeros, so the fixed-size reads of number, text_field and
name_letter always fit, and their paths for the end of the input go. That also removes the
one libc call left on the per-record path: LLVM had merged name_letter’s 24-byte copy and its
shorter end-of-input copy into one memcpy with a variable length. An audit of the per-record
path finds no other call; the bcmp in NameSet::read runs only for names over 24 bytes.
Two smaller cuts: guess_bounds computes its cut in a closure, and the output loop filters out
countries without records.
Local, on top of step 13 (P-cores, a loaded machine, 151 interleaved runs, median / min):
42.34 / 39.60 → 42.08 / 39.53 ms. perf stat -r 10, three interleaved rounds: instructions
1.637 → 1.549 G (-5.4%), cycles and task-clock flat, page faults 6,390 in both. Merged with
step 14, S 534 → 523, and 522 after inlining the single-use KEY constant, which leaves the machine code
identical. Gate: 307 pass, 0 fail; full seeds 1 to 7; the 400 random and 400 hostile
cases at 1, 3, 12, 37 and 64 threads; the forced-cut test on 490,079 offsets of 72 files.
Step 16: the region lookup prefetched, four records at a time
At step 15 the byte load in Regions::group was the parse loop’s one load that missed L2: 40% of
all L2 misses and 6.5% of all cycle samples (P-cores, perf record). The table is 1 MB, which
does not stay in a core’s 1.25 MB L2 next to the input and the name sets, so the load goes to L3
(per run, 4.3 M loads hit L3 and 54 K missed it). With the lookup replaced by id & 127, a wrong
output, the median wall time fell 4.9%, the most that hiding the load could give.
The worker now parses and posts four records, and prefetches each one’s byte in the table as soon as its region id is parsed. Only after the fourth does it look up the four groups, OR each group into the last word of its letter, which no one reads before the barrier, and add each record to its group. A prefetch retires without waiting for its line, so it does not hold up the reorder buffer the way the load did.
On top of step 15, P-cores, wall time of interleaved runs (ab.py, 151 runs each), median /
min: 41.09 / 40.07 → 39.85 / 38.96 ms. perf stat -r 10, three interleaved rounds: cycles
0.953 to 0.958 → 0.919 to 0.920 G (-3.7%), task-clock 425 to 427 → 411 to 412 ms, instructions 1.550 →
1.655 G, page faults 6,390 in both. In 101-run sessions, batches of 3 and 4 measured -2.8%, 2
-1.2%, 6 -1.8% and 16 -1.9%, and the batch of 4 without the prefetch +1.3%. S 522 → 534.
Variants that did not stay, against step 15 in the same sessions:
- The prefetch alone, with the lookup where it was: flat (41.05 against 41.07 ms).
- Each record’s lookup one record late instead of in batches: -0.8% to -1.1%. The record carried past the next parse spilled to the stack, 20 more instructions per record.
- The batch as a
Vecin the record loop: +1.9%. - A non-temporal prefetch of the input 1 KiB ahead, to keep it out of L2: +2.2%.
- Rounds of 32 KiB: +3.5%. Rounds of 128 KiB with 512-letter mailboxes: flat, with more memory.
- A rank table for the regions on top of this step: one word per 32 ids with their presence bits and the count of the regions before them, and one group byte per region, 450 KB in all. It saved 134 page faults, about 0.5 MB, but cost +6.0% wall time and +12% task-clock: the second load depends on the first, and the prefetch covers only the first.
Correctness checks: the gate (307 pass, 0 fail); full seeds 1 to 7; the 400 random and 400 hostile cases at the default thread count and at 1, 3, 12, 37 and 64 threads; the same cases on a build with 100-byte rounds and 3-letter mailboxes, which ends most rounds with a full mailbox and a partial batch, at 1, 2, 3, 12 and 64 threads; and the forced-cut test on 490,079 offsets of 72 files.
Step 17: a static-pie build
-C target-feature=+crt-static in .cargo/config.toml (free on S) links the binary as a
static PIE, so the process starts without the dynamic loader, as track A has done since its
step 14. ab.py, 40 interleaved runs on top of step 16, median / min / mean: 40.14 / 38.97 /
42.65 ms dynamic, 39.70 / 38.86 / 40.73 ms static. Gate: 307 pass, 0 fail; the image built
offline and run with the harness’s sandbox flags gives seed 1’s hash.
Steps 16 and 17 went to the board in one push, so both rows cite run-521d52addb7b.
Step 18: a leaner rewrite
Lines were what kept C behind: at S 534 against an Sref of 108, they cost about 1.9 points
next to an entry of the same speed at S 298. So the design was written again with only the
parts that measured as paying. Spec §2.2 makes the run starts exact: inside a note an LF is
followed by a lowercase word or a quote, never by a digit or a BOM, so the first LF after a cut
that a digit or a BOM follows starts a record. That drops the guessed starts, the check that
the runs tile the file, the rerun when they don’t, and the sentinel record. The name exchange
keeps its design (owners, 32-byte letters, 64 KiB rounds, one barrier per round) with plain
mailboxes instead of the Exchange type. Each mailbox now holds a whole round’s worst case,
64 KiB of 11-byte records, so no round ends early, every worker takes part in as many rounds
as the longest run needs, and the barrier only counts arrivals: a waiter spins, then sleeps in
50 µs steps, where step 17’s parked until the last worker to arrive unparked it. The field
parsers, the region table and the name sets keep their designs, less step 11’s map for groups
past 254 countries: more than 255 countries now stop the join with an error (§2.3 has 240),
and a name’s entry is always one 64-byte line. S 534 → 323.
ab.pyagainst step 17, interleaved, medians / minimums: 101 runs twice, 39.82 / 38.86 → 39.43 / 38.07 and 39.96 / 38.59 → 39.55 / 38.31 ms; 60 runs on seed 1, 39.92 / 38.77 → 39.26 / 37.92 ms; 60 runs on seed 3, 40.02 / 38.19 → 39.49 / 38.35 ms.- memory.peak: 60 alternating rounds, medians 11.890 → 11.880 MiB; a 6-round sample in another session, 12.17 to 12.94 → 12.27 to 13.86 MB.
- Correctness: the gate, 307 pass, 0 fail; full seeds 1 to 7 give the reference hashes; the 402 fuzz cases pass at 1, 3, 12, 37 and 64 threads and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300 tiny seeds pass at 10 thread counts with 100-byte rounds; the image built offline and run with the harness’s sandbox flags gives seed 1’s hash. Of step 11’s region sets, the one with shuffled ids passes, and the two with 689 and 692 countries stop with the error.
Step 19: 5 fewer lines, the same machine code
Line cuts on step 18 that leave .text and .rodata byte-identical to step 18’s binary
(objcopy and cmp). batch and parsed are declared together, and so are counts and
arrived; the step past an escaped quote sets pairs and end in one assignment;
parse_regions finds the body after the header in one line; and the crate’s two cast lint
exceptions move to Cargo.toml, next to the one already there. Dropped: names and sent
declared together, which moved one allocation’s code. S 323 → 318. Gate: 307 pass, 0 fail;
clippy reports no warnings.
Step 20: 2 fewer lines, the same machine code
Two more declarations merged on step 19, with .text and .rodata byte-identical to step 19’s
binary: each worker sets its position, its run’s end and its groups in one statement, and
text_field sets the field’s start and its scan position, both just past the opening quote, in
one. Dropped because the machine code changed: the round’s half and round_end declared
together, and regions.csv mapped inside the parse_regions call, which drops its path later.
S 318 → 316. Gate: 307 pass, 0 fail; clippy reports no warnings.
Step 21: 3 fewer lines, the same machine code
On step 20, with .text and .rodata byte-identical to step 19’s binary: map_file makes its
two mmap calls as two statements, each with its own safety comment and its flags named above
it, instead of one unsafe block, and the byte loop of number updates the value and the
position in one assignment. Dropped because the machine code changed: merge setting the min
and the max in one assignment. S 316 → 313. Gate: 307 pass, 0 fail; clippy reports no warnings.
Step 22: 1 fewer line, the same machine code
NameSet::read names the letter’s 32-bit hash once and takes the first slot and the tag from
it, where it cast key[3] twice, so its three declarations before the probe become two.
.text and .rodata are byte-identical to step 21’s binary. S 313 → 312. Gate: 307 pass,
0 fail; clippy reports no warnings.
Steps 21 and 22 went to the board in one push, so both rows cite run-af528e5f49cc.
Step 23: 17 fewer lines outside the record loop
Cuts on step 22 outside the record loop. The worker’s code differs from step 22’s only at its end and in register choices, a few stack moves and alignment padding:
- Each worker gives its run’s pages back in two lines at the end of its closure, instead of
through
release. The range now runs from the page that holds the run’s first byte to the page that holds its last, wherereleasekept to the pages wholly inside the run. A neighbour that still reads a shared page, at the end of the run before, maps the same bytes from the file again, as a long name compared after the release already could. 4 lines. parse_regionskeeps the header’s LF at the start ofbody, so a row starts atpexactly whenbody[p - 1]is an LF, and each cut is onefind(3 lines). Marking the countries that occur along with the largest id, and writing each region’s group, take one statement each (5 lines), andCODESis written out at its one use (1 line).- In
join, a run’s start is one closure, and the rounds are counted and the parts merged in one statement each. 4 lines.guessis nowrun_start, since step 18 made the starts exact.
S 312 → 295. ab.py against step 22, 101 interleaved runs, medians / minimums, two sessions:
seed 1, 39.28 / 38.21 → 39.07 / 38.24 and 39.25 / 38.01 → 39.16 / 38.17 ms; seed 3,
39.18 / 38.19 → 39.04 / 37.78 and 39.08 / 38.21 → 38.90 / 38.04 ms. memory.peak, 40
alternating rounds: medians 11.950 → 11.930 MiB, means 12.024 → 11.915 MiB. Correctness: the
gate, 307 pass, 0 fail; full seeds 1 to 7 give the reference hashes; the 402 fuzz cases pass at the
default thread count, at 1, 3, 12, 37 and 64 threads, and with 100-byte rounds at 1, 2, 3, 12
and 64; the 300 tiny seeds pass at 10 thread counts with 100-byte rounds; clippy reports no
warnings.
Step 24: 1 fewer line
main maps both input files through one closure that takes the file’s name. Only main’s code
changes, with map_file now inlined into the closure, and NameSet::read moves 96 bytes down
the binary, onto a 32-byte boundary instead of a 64-byte one. S 295 → 294. ab.py against
step 23, interleaved, medians / minimums: 101 runs on seed 1, 39.30 / 38.16 → 39.31 / 38.34 ms;
101 runs on seed 2, 39.24 / 37.95 → 39.21 / 38.06 ms; 61 runs on seed 3, 39.08 / 38.17 →
39.09 / 38.15 ms. Correctness: the gate, 307 pass, 0 fail; full seeds 1 to 7 give the reference
hashes; the fuzz cases, the tiny seeds and the region sets give step 23’s results; a missing
input directory still stops with the file’s path in the error.
Step 25: fewer instructions to build and post a letter
Two cuts in the record loop on step 24:
name_letterkeeps the firstlenbytes of a name by ANDing its three words with a 24-byte window ofKEEP, 24 bytes of ones and then 24 of zeros, taken from24 - lenon. Each word was masked by a shift of au128by its own byte count, which took a clamp and a 128-bit shift per word.- A worker keeps, for each owner, the index of its next letter in that owner’s mailbox instead
of the number of letters it posted there this round. A letter’s four stores, and the batch’s
later write of its group, address the mailbox by that index alone, where each record
computed
(mailbox(half, me, to) * MAILBOX + sent[to]) * 4. The counts come from the indices once per round.
perf stat -r 10, twice: instructions:u 1.667 → 1.594 G, 22 fewer per record, and cycles:u
0.91 → 0.87 G. S 294 → 296. ab.py against step 24, 40 interleaved runs, medians / minimums:
39.27 / 38.23 → 37.27 / 36.41 ms and 39.31 / 38.45 → 37.46 / 36.52 ms; in two earlier sessions,
on a build that differed only in the type of the window, 39.23 / 38.56 → 37.33 / 36.55 ms and
39.40 / 38.48 → 37.45 / 36.82 ms. memory.peak, 17 alternating rounds: medians 12.63 → 12.77 MB,
means 12.84 → 12.69 MB, the same within this machine’s spread. Correctness: the gate, 310 pass,
0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; the 402 fuzz cases pass at the
default thread count, at 1, 3, 12, 37 and 64 threads, and with 100-byte rounds at 1, 2, 3, 12
and 64, where that build now asserts that no worker’s index runs past its mailbox; the 300 tiny
seeds pass at 10 thread counts with 100-byte rounds; of step 11’s region sets, the one with
shuffled ids passes, and the two with 689 and 692 countries stop with the error; clippy reports
no warnings.
The board’s run, run-b89d1be25a5e, drew 34.8 ms, against 34.9 ms for step 24’s: one draw on the
board does not show the 5% measured here.
A second run of the step 25 code, run-835825f2db93 (commit 7128f44, which changed only track A),
measured 34.4 ms, 12.7 MB and 76.9 points.
Step 26: the long-name compare out of the probe
NameSet::holds compared the text of two long names, which only names over 24 bytes need, in
the same expression as the 32-byte key compare. Inlined into NameSet::read, the slice bounds
checks of that compare were hoisted out of the probe loop into the setup of every letter, about
a dozen instructions and a few spills per letter for names that are almost never long. The
compare is now same_text, a cold function that the probe calls only when two long names’
keys match.
perf stat -r 10, twice: instructions:u 1.592 → 1.533 G, 18 fewer per record, and cycles:u
0.860 → 0.837 G. S 296 → 299. ab.py against step 25, 40 interleaved runs, medians / minimums:
37.20 / 36.45 → 36.76 / 35.92 ms and 37.52 / 36.37 → 36.69 / 35.94 ms; on a build whose
same_text named the two slices through a closure, 37.39 / 36.66 → 36.48 / 35.80 ms and
37.30 / 36.54 → 36.81 / 35.71 ms. memory.peak, 10 alternating rounds: medians 12.37 → 12.59 MB,
means 12.49 → 12.69 MB, inside this machine’s spread of 12.1 to 13.6 MB for both. Correctness: the
gate, 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; the 402 fuzz cases,
two of them sets of long names, pass at the default thread count, at 1, 3, 12, 37 and 64
threads, and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300 tiny seeds pass at 10 thread
counts with 100-byte rounds; the region sets give step 25’s results; clippy reports no
warnings.
Step 27: a plain static executable
-C relocation-model=static joins +crt-static in .cargo/config.toml, as in track A: the
binary is a plain static executable at a fixed address instead of a static PIE that relocates
itself before main.
Local, turbo off: ab.py against step 26, 40 interleaved runs, five rounds: medians 36.54 →
36.47, 36.65 → 36.49, 37.50 → 36.60, 36.47 → 36.17 and 36.61 → 36.53 ms, minimums 35.92 → 35.57,
35.83 → 35.86, 35.53 → 35.73, 35.61 → 35.60 and 35.85 → 35.56 ms. The third round ran on a busy
machine (means 49.9 and 45.5 ms). S unchanged at 299. Gate: 310 pass, 0 fail.
Step 28: a record’s quotes from one mask
text_field jumped from quote to quote, and each jump compared the next 32 bytes with " and
branched on what it found: a name and a note took at least two such scans, and every "" one
more. Now the hot loop compares the 64 bytes from a record’s name with " once, two AVX2
compares packed into one 64-bit mask (quotes), and both fields take their quotes from that
mask, lowest first, with tzcnt. An escaped quote is two neighbouring bits, cleared together,
and the closing quote is one whose next bit is clear. On full seed 1 the 64 bytes hold the
name’s and the note’s closing quotes for 97.8% of records (from the name’s start to the note’s
closing quote: median 37 bytes, 99th percentile 65). A field that runs past the mask moves it
on, to its last bit’s quote when that bit is set, because the byte after that quote lies past
the mask and could be its pair. PAD grows from 32 to 64 bytes, so the 64-byte read
always fits.
The compares are written with intrinsics. As a loop over the 64 bytes, or as two calls of the 32-byte loop that step 6 used, the compare stayed scalar once inlined into the worker, at about 2.9 G instructions in all, and as a closure it was called out of line twice per record.
perf stat -r 10, twice: instructions:u 1.536 → 1.501 G (11 fewer per record), cycles:u
0.839 → 0.767 G, branch misses 3.71 → 2.87 M. S 299 → 311. ab.py against step 27, 40
interleaved runs, medians / minimums: 36.45 / 35.38 → 33.79 / 33.13 ms and
36.22 / 35.34 → 33.79 / 33.24 ms; the same source on step 26’s static PIE build, against step
26: 36.40 / 35.72 → 34.10 / 33.20, 36.60 / 35.68 → 34.28 / 33.20,
36.99 / 35.75 → 34.41 / 33.43 and 36.39 / 35.77 → 34.16 / 33.44 ms. memory.peak, alternating
rounds: against step 27 (8 rounds) medians 12.82 → 12.89 MB, means 12.98 → 12.77 MB; against
step 26 (10 rounds) medians 13.54 → 12.51 MB, means 13.18 → 12.72 MB; all inside this
machine’s spread of 11.7 to 14.0 MB, and no allocation changed. Correctness: the gate, 310 pass,
0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; the 402 fuzz cases pass at the
default thread count, at 1, 3, 12, 37 and 64 threads, and with 100-byte rounds at 1, 2, 3, 12
and 64; the 300 tiny seeds pass at 10 thread counts with 100-byte rounds; the region sets give
step 27’s results; clippy reports no warnings.
Step 29: plain loads and a cold insert in the mark loop
NameSet::read took each letter as four atomic loads, which the compiler may not merge, and
then spent seven more instructions putting the 32-byte key in one vector for the compare in
holds. A round’s letters are read only after the barrier their posters passed, and none is
stored again until every worker has passed the next one, so read now views its mailbox as
plain [u64; 4] letters and loads each key at once. insert, inlined into the probe, took its
registers and spilled every letter’s key; a name is new only once, so insert is now #[cold]
and out of line. And a letter’s group is read as a byte, which it always fits (parse_regions
stops at 255 countries), so the word of its bit takes no bounds check.
perf stat -r 5, twice: instructions:u 1.505 / 1.511 → 1.450 / 1.440 G, 17 fewer per record;
without the cold insert, 1.481 G. S 311 → 313. ab.py against step 28, 101 interleaved runs,
medians / minimums: 35.09 / 33.13 → 34.21 / 32.56 ms and 35.18 / 33.29 → 34.57 / 32.78 ms; the
same source without #[cold] against with it, 34.76 / 32.85 → 34.70 / 32.43 ms and
34.63 / 32.79 → 33.90 / 32.35 ms; on step 27, against step 27, 36.35 / 35.53 → 35.91 / 35.09 ms
and 36.33 / 35.53 → 35.81 / 35.07 ms. memory.peak, on step 27, 10 seeds × 11 alternating
rounds: the per-seed medians move by +0.07 MB on average (-0.48 to +0.85 MB), inside this
machine’s spread, and no allocation changed. Correctness: the gate, 310 pass, 0 fail; full
seeds 1 to 7 and 10 to 12 give the reference hashes; the 400 fuzz cases pass at the default thread
count, at 1, 3, 12, 37 and 64 threads, and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300
tiny seeds pass at 1, 3, 12 and 64 threads with 100-byte rounds; 40 generated sets of names
pass at 1 to 4 CPUs; clippy reports no warnings.
Step 30: 5 fewer lines
Cuts on step 29 in the name set, merge and main. Three leave the machine code as it was:
.text is byte-identical to step 29’s binary, and .rodata differs only in the line numbers of
src/main.rs panic locations (tools/rodiff.py).
NameSet::inserttakes its key as four words,[a, b, c, d], and builds the entry inside itspush.NameSet::readtakes each letter as its four words and the group and the key from them in one statement.mainimportsfs::write, so the output’s write and its error fit one line.
Two change the machine code:
mainreads each directory asstd::env::args().nth(i), with no iterator kept for the two. Onlymain’s code changes, and the code after it moves.mergesets the min and the max in one assignment, which swaps two stores in the record loop. Step 21 dropped this cut because the machine code changed; it measured the same here.
ab.py against step 29, 101 interleaved runs per build, three rounds, medians: step 29 33.48,
33.57 and 33.77 ms; the three identical cuts 33.66, 33.50 and 33.86 ms, which is the spread of
the same code; with merge 33.58, 33.53 and 33.72 ms; with nth 33.50, 33.45 and 33.70 ms; all
five 33.48, 33.55 and 33.59 ms. Two rounds of 40 runs, step 29 against all five: 34.86 → 34.78
and 37.90 → 36.99 ms, on a busy machine. S 313 → 308. Gate: 310 pass, 0 fail; clippy reports no
warnings; a missing input directory, a missing output directory and no arguments stop with the
same errors as before.
Dropped: format_output building each line with one format! and collecting the lines, 3
lines. With no write! into a Vec<u8> left, the binary loses the drop glue of io::Write’s
adapter, which sits in front of the worker, so the worker’s code moves by 16 bytes; on step 28
that build measured 0.26 to 0.52 ms slower than the same build without it, in three rounds. Also
dropped: the rehash’s probe as one find over hash.., 2 lines, which clippy’s
maybe_infinite_iter flags.
Step 31: the sources mounted, not copied
The Dockerfile’s build stage mounts its context (RUN --mount=type=bind,target=/src) instead of
copying it with COPY . ., and cargo builds into --target-dir /out, since the mount is
read-only; track A does the same since its step 45. harness/dockerfile_check.py accepts a bind
mount of the context, and every builder that builds us is BuildKit: Depot, the board’s rootless
BuildKit fallback and final scoring’s docker build. A local docker build --network=none of
the old and the new Dockerfile gave binaries byte-identical to each other and to a cargo build of
step 30, so T and M cannot move. S 308 → 307. Gate: 310 pass, 0 fail.
Step 32: the probe ends at its line
NameSet::read probed for an entry’s index and then indexed the entries with it once more to
mark the bit. On a hit holds had already checked that index, but the check came again after
the loop, where the index that insert returns joins it. The probe now ends at the line itself
and insert returns the line it pushed, so a hit’s index is checked once. The test for a long
name, key[3] >> 32 == LONG, moved from holds into same_text, which only runs when two keys
share their hash and length: in the probe, its two 64-bit constants held two registers for every
letter.
instructions:u on one E-core, so one worker and no waiting: 1428.20 → 1402.29 M, 7.0 fewer per
record; the line alone 1408.85 M, the long-name test alone 1411.93 M. perf stat -r 5 on the
P-cores, twice: 1.442 / 1.443 → 1.415 / 1.417 G. ab.py against step 31, which has step 30’s
binary, 101 interleaved runs, medians / minimums: 33.50 / 32.31 → 33.05 / 32.07 ms and 33.59 /
32.60 → 33.17 / 32.50 ms. The worker’s code stays where it was; only NameSet and same_text
change. S 307 → 309. No allocation changed. Correctness: the gate, 310 pass, 0 fail; full seeds
1 to 7 and 10 to 12 give the reference hashes; the 400 fuzz cases pass at the default thread count, at
1, 3, 12, 37 and 64 threads, and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300 tiny seeds
pass at 1, 3, 12 and 64 threads with 100-byte rounds; 40 generated sets of names pass at 1 to 4
CPUs; clippy reports no warnings.
Dropped, by instructions on one E-core against this step’s 1402.29 M: the key compare as an OR
of XORs, which keeps the key out of memory but has LLVM build it from four scalars, 1444.50 M;
holds borrowing the key, 1418.49 M; insert taking the letter where it lies, 1435.00 M; and
same_text taking the key’s offsets by value, 1402.29 M, the same code.
Step 33: one pool for the regions and the join
Step 32 built the region table on a pool of its own before the join: each thread listed the rows
of one share of regions.csv, then the main thread numbered the codes from the lists and wrote
the array, and only then started the join’s threads. On an instrumented copy of step 32 (local,
P-cores, ms after main began), the region threads ran from 0.41 to 0.97, the numbering ended
at 1.51 and the array’s writes at 2.35, and the join’s workers started at 2.45 to 2.63. Now the
join’s workers build the table before their rounds, with no lists, in two steps that end at the
barrier the rounds use, which moved into barrier. In the first, each worker reads its share of
the rows (region_rows) and ORs a bit per country code into a shared set of 26³ bits. In the
second, every worker numbers the codes from the bits, in index order as the serial pass did, and
reads its rows again to write each id’s group. With a timestamp at the start of each worker’s
rounds, the rounds began 1.33 to 1.70 ms after main began, against 2.44 to 3.73 ms for step 32
(4 runs each). The name sets are no longer freed, either: each worker’s munmap calls stopped
the other workers for a TLB flush, and the exit unmaps the pages anyway.
Mapped in by every worker, the array’s pages raised memory.peak by 1.1 MiB, 13.04 against 11.91
MiB (medians, 24 alternating runs), and by 0.6 to 1.4 MiB on each of full seeds 1 to 7 and 10 to 12
(3 runs each), though smaps at exit showed less anonymous memory than step 32’s. memcg charges
a CPU 64 pages at a time and keeps the rest of the batch for that CPU’s next pages, and
memory.peak counts the whole batch. At the end of the rounds memory.current exceeded anon +
kernel in memory.stat by a median 2.1 MiB, against 1.2 MiB for step 32 with the forget (12
and 18 runs). More pages per worker confirmed it: 16 or 32 more each, 0.75 or
1.5 MiB in all, left the peak at 13.10 and 13.16 MiB (13.10 without them), and 48 raised it to
15.27 MiB. So the main thread maps the array’s pages in before the spawn with
madvise(MADV_POPULATE_WRITE), on one CPU as step 32’s writes were: 11.79 against 11.74 MiB
(medians, 30 alternating runs; the highest of 5 runs, which the board takes, 12.20 against 12.15
MiB by resampling). The table of code numbers, 17.5 KB per worker, is freed before the worker’s
groups are made, which reuse its pages: 0.23 MiB less anon.
ab.py against step 32, 50 interleaved runs, two rounds, medians / minimums: 32.60 / 31.98 →
31.58 / 30.87 ms and 33.04 / 32.17 → 31.82 / 31.01 ms. instructions:u on one E-core: 1402.29 →
1403.90 M, the rows now read twice. S 309 → 319. Correctness: the gate, 310 pass, 0 fail; full
seeds 1 to 7 and 10 to 12 give the reference hashes; the 400 fuzz cases pass at the default thread
count, at 1, 3, 12, 37 and 64 threads, and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300
tiny seeds pass at 1, 2, 3, 5, 7, 12, 16, 23, 37 and 64 threads with 100-byte rounds; clippy
reports no warnings.
Dropped: the pages written from the main thread one byte each, the same memory.peak and 0.16 to
0.28 ms slower (ab.py, 50 runs, three rounds); the pages written by worker 0 during the first
step, 12.43 against 11.96 MiB for step 32 (16 runs); and the array written by worker 0 alone in
the second step, 12.89 against 12.30 MiB for step 32 with the forget (6 runs). Freeing the name
sets as before measured 32.04 / 31.57 and 32.09 / 31.60 ms against 31.94 / 31.38 and 32.03 /
31.57 ms with the forget (50 runs, two rounds), with memory.peak 12.11 against 11.86 MiB (24
runs).
Step 34: 44 fewer instructions per record
Step 33 ran 427 instructions per record, and a profile of uops_issued.any by source line (a
profiling build of step 33, 20 runs) found no block that dominates: the three number parses
were 18% of the samples, the name set’s key compare 11%, and the posting, the batch and the
bounds checks a few percent each. The cuts, each measured as instructions:u and cycles:u with
perf stat (20 interleaved runs against step 33, medians):
- The amount as one number.
numbertakes a count of decimals after its stop. The word is shifted so that the stop lands in byte 7 minus the decimals for every length, and the bytes below it move up over it, so the same three multiplies give the cents. §2.2 bounds the amount at 99,999.99, so its digits and its dot fit in one word; a longer one takes the byte loop, which reads the decimals too. -0.4% instructions, -1.3% cycles. - The batch made once per worker instead of zeroed for every batch: with the amount, -0.8% / -2.5%.
sent[to]read once. The four stores of a letter made the compiler load it again for each, with a bounds check. On step 32’s code this measured slower (see the experiments below); on top of the amount it measured -4.7% / -3.3%, and borrowing the letter’s slot once instead,&boxes[sent[to]], -4.3% / -2.9%.- The BOM test from the id’s word. A record starts with a digit or a BOM, so the id is parsed first and parsed again from past the BOM when its first byte is 0xEF, which the id’s word already holds: no load and no bounds check for the test. On top of the amount, -2.7% / -2.7%. The four together: -7.4% / -5.1 to -5.8% (three sessions).
- The stop as the first byte below
0. Subtracting0from every byte replaces the XOR with the stop: every stop,,or., lies below0, and the difference already holds each digit’s value, so an id and a region id need no mask. On top of the four: -10.8% / -7.4 to -8.0%. - The input prefetched 448 bytes ahead of each record. PEBS
mem_load_retired.l1_misson aprofilingbuild put 10.1 M L1 misses on a run: 73% on the name set (its slots 27%, the key compare 26%, the group’s distinct count 20%), 18% on the groups’ merge and 7% on the input (the quote masks’ 64-byte loads and the number words). With the prefetch, L1 misses 10.11 → 9.39 M, instructions +0.5% and cycles -1.1% (40 interleaved runs); 384 bytes ahead, -1.0%.
On AC power again (profile performance, turbo off), ab.py, 41 interleaved runs, two
rounds: medians 32.26 and 32.15 → 29.84 and 29.81 ms, minimums 31.34 and 31.29 → 29.13 and
28.96 ms, 7.1 to 7.5% faster. The counters were measured on battery power before that (local,
P-cores): perf stat, 40 interleaved runs, two rounds, instructions:u 1418.0 → 1271.2 M (-10.4%),
cycles:u medians 768.5 → 703.0 M and 764.2 → 699.1 M (-8.5%), minimums 758.3 → 694.4 M and
754.6 → 694.1 M. memory.peak, 30 alternating runs: medians 12.01 → 11.96 MiB, the highest of 5
by resampling 12.52 → 12.37 MiB. S 319 → 326. Correctness: the gate, 310 pass, 0 fail; full seeds
1 to 7 and 10 to 12 give the reference hashes; the 400 fuzz cases and the two long-name sets pass at
the default thread count, at 1, 3, 12, 37 and 64 threads, and with 100-byte rounds at 1, 2, 3, 12
and 64; the 300 tiny seeds pass at 1, 2, 3, 5, 7, 12, 16, 23, 37 and 64 threads with 100-byte
rounds; clippy reports no warnings. The board’s run, run-91b80b654f7a, measured 26.9 ms and
12.2 MB, against 29.1 ms and 12.2 MB for step 33’s.
Branch misses, 0.87 per record (2.87 M per run), are 55% the name set’s probe, which step 32’s
eight-slot probe already took on with no gain (see the experiments below), and 34% the pair test
in text_field, on names and notes with an escaped quote. A branchless pair test costs more
instructions than the misses’ cycles, which the hyperthread sibling partly hides.
Dropped, on battery power, perf stat, 20 interleaved runs against the code before them:
- Each letter posted right after its name, so that its four words were not held across the note and the numbers: instructions -2.7%, but cycles +2.0%, and backend-bound slots 22.0 → 26.6%.
- The batch holding a reference to the letter’s last word instead of its slot: -0.2% instructions, +1.0% cycles.
- The owner count in a local, instead of the captured thread count: +0.3% instructions, cycles within noise.
- A zero byte past the region table, so that the lookup takes
mininstead ofget: +1.3% instructions, +1.8% cycles. - Distinct names counted in a dense array per worker, 2 KiB, instead of in the groups, whose lines took 20% of the L1 misses in the marking loop: -1.1% instructions, cycles within noise.
Step 35: 65 fewer instructions per record
Step 34 ran 383 instructions per record, and its profiles by source line pointed at the field
parses: the two number parses of the region id and the amount, each a chain of shifts,
multiplies and branches, and the walk over each field’s quotes. The cuts, each measured with
perf stat against the code before it (20 to 30 interleaved runs, medians; on battery power at
first, so instructions:u and cycles:u only), and then timed again on AC power with ab.py (41
interleaved runs, two rounds, medians, P-cores):
- The region id and the amount from one vector. §2.2 bounds region ids at 9,999,999 and
amounts at -999.99 to 99,999.99, so the two fields fit in 16 bytes. One SSE compare finds the
comma and the dot, one
pshufb, with a control picked by their places, right-aligns both numbers’ digits with the dot dropped, and three multiply-adds give both values at once. Fields past those bounds that §2.1 still allows take two number parses, as before.numberloses its decimals, which only the amount used. Instructions -9.0%, cycles -5.2 to -5.7% (two sessions);ab.py-5.2% and -5.3%. - A CRC32 name hash instead of
FxHash: onecrc32per word and no fold, and its 32 bits depend on every word. -3.5% / -1.7%, with branch misses the same (2.91 → 2.92 M), so the names spread over the slots as well;ab.py-1.2% / -1.4%. - The name set’s key in one AVX2 register, from one load and one AND of the letter, compared
with an XOR and
vptestagainst the first 32 bytes of the entry. The cold insert and the long-name compare take the key as a vector too: when they took four words, the probe stored every letter’s key to the stack for them (+1.2% instructions, +1.0% cycles). -2.7% / -1.4%;ab.py-1.0% / -1.7%. sent[to]without its bounds check.tois a 32-bit hash times the thread count, shifted down by 32, so it is below the thread count. -1.7% / +0.1%,ab.py-0.2% / +0.1%; but on the final code, putting the check back cost 2.2% more instructions and 1.4% more cycles, so it stays.- The name and the note from one mask of the 64 bytes at the name. The prefix XOR of the
quote mask, one carry-less multiply by all ones as in simdjson, marks the bytes inside quotes;
the first two commas outside end the two fields, and a field’s length is its raw length less
half its quotes. There is no branch per quote, where
text_fieldwalked the quotes one by one and mispredicted on escaped ones. The 2.2% of records whose note ends past the window take a loop over 64-byte blocks that carries the parity from block to block. -2.0% / -2.6%, branch misses 2.89 → 1.89 M, branches 136.8 → 107.1 M;ab.py-2.4% / -2.3%. - The
pshufbcontrols 16-byte aligned, as vectors, so that none straddles two cache lines: cycles -0.2%,ab.pywithin noise.
On AC power (profile performance, turbo off), ab.py, 41 interleaved runs, two rounds, against
step 34: medians 29.66 and 29.46 → 26.72 and 26.50 ms, minimums 28.66 and 28.72 → 25.73 and 25.69
ms, 9.9 to 10.6% faster. perf stat, 20 interleaved runs: instructions:u 1272.1 → 1055.2 M (-17.0%,
383 → 318 per record), cycles:u 684.4 → 601.9 M (-12.0%). memory.peak, 30 alternating runs, two
rounds: medians 12.00 → 12.19 MiB and 12.05 → 12.17 MiB, the highest of 5 by resampling 12.29 →
12.54 MiB and 12.41 → 12.67 MiB. S 326 → 387: the step adds 61 lines, kept down by one glob import
for the intrinsics and by the loss of text_field and quotes. Correctness: the gate, 310 pass, 0
fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; the 400 fuzz cases and the two long-name
sets pass at the default thread count, at 1, 3, 12, 37 and 64 threads, and with 100-byte rounds at
1, 2, 3, 12 and 64; the 300 tiny seeds pass at 1, 2, 3, 5, 7, 12, 16, 23, 37 and 64 threads with
100-byte rounds; six generated files of edge cases (region ids of 1 to 8 digits against amounts of 1
to 7, with signs and leading zeros, and names and notes whose quotes, escapes and commas fall around
the 64-byte window and the 24-byte letter) match the reference at 1, 2, 3, 7, 12 and 64 threads and
with 100-byte rounds; clippy reports no warnings.
A profile of cycles by part on the step’s code (a profiling build, 60 runs): marking the
letters (NameSet::read) 27.4%, the rest of the record loop 9.6%, region_amount 7.8%, the
barrier 7.6%, text_fields 7.3%, the merge 4.4% and name_letter 3.9%.
Dropped, perf stat, 20 interleaved runs against the code before them, on battery power unless
noted:
- The id parsed by SSE too: instructions +0.1%, cycles the same.
- The input prefetched 576 or 704 bytes ahead instead of 448: instructions +0.02% / +0.09%, cycles medians +1.6% / +2.6%, minimums the same.
- The marking loop prefetching the slots and entries of the letters 8 or 16 ahead, two shapes: L1 misses 9.7 → 5.5 M and L2 misses 2.65 → 0.83 M per run, but instructions +8.6 to +9.0% and cycles +0.6 to +1.7%, and the marking took as long, so it does not wait on those misses.
- The probe’s slots read without bounds checks: instructions -0.3%, cycles +0.3%.
- The slow text path counting its quotes byte by byte, which takes fewer lines (on AC power, on the final code): instructions +1.3%, cycles +1.5%; 2% of the records is enough for that.
The board’s run, run-6252826712db, drew 25.2 ms against 27.2 ms for step 34’s second run, run-835b63d0f252, and 26.9 ms for its first: -6 to -7%, less than the -10% measured here, while the 61 more lines cost about as many points as 5% of T.
Step 36: the batch’s loads forwarded from its stores
The record loop stores each record’s fields into the batch of four and loads them back for the
merge once the batch is parsed. In step 35’s code the compiler had put two of them, the id and
the amount, side by side, and loaded them as one 16-byte vector. A load that spans two stores
still in the store buffer cannot take its bytes from them, so it waits until both reach the
cache: ld_blocks.store_forward counted 0.44 to 0.64 M such loads per run, almost all in the
merge. Three changes, none of which adds a line:
- The batch’s fields in another order. A tuple’s layout is the compiler’s choice. In this
order the id, the amount and the name’s length, the three values that the merge puts into one
vector with the count, lie apart, so each is loaded on its own: store-forward blocks 0.44 M →
3.3 k per run. Alone it built the vector from three loads instead of two: instructions +1.4%,
ab.py+0.7%. - The group as one byte. The group went into the letter’s last word with a load, an OR and a
store. One byte store now writes byte 30, bits 48 to 55, which
name_letterleaves 0. With the new order,ab.py-0.2% to -1.1% against step 35 in six rounds. - The letter by reference. The batch holds a reference to the record’s letter instead of its slot, so the group’s store takes no second bounds check or address computation.
On AC power, ab.py, 41 interleaved runs, two rounds, against step 35: medians 26.99 and 27.01
→ 26.39 and 26.54 ms (-2.2% and -1.7%), minimums 26.24 and 26.13 → 25.89 and 25.92 ms; three
earlier sessions of the same code measured -2.4%, -1.6% and -2.2%. perf stat, 20 interleaved
runs: instructions:u 1055.2 → 1024.6 M (-2.9%, 318 → 309 per record), cycles:u 599.9 → 590.1 M
(-1.6%). memory.peak, 15 alternating runs: medians 12.55 → 12.36 MiB. S 387 → 387. Correctness:
the gate, 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; the 400 fuzz
cases and the two long-name sets pass at the default thread count, at 1, 3, 12, 37 and 64
threads, and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300 tiny seeds pass at 1, 2, 3, 5,
7, 12, 16, 23, 37 and 64 threads with 100-byte rounds; the six files of edge cases match the
reference at the default thread count, at 1 and 37 threads, and with 100-byte rounds at 3 and 64;
clippy reports no warnings.
Where step 35’s slots go, top-down at level 2 (perf stat --topdown, P-cores): retiring 54%
(light operations 51.2%, heavy 2.7%), bad speculation 8.6% (branch mispredicts 8.3%), frontend
11.6% (latency 8.4%, bandwidth 3.2%) and backend 24.8% (core 17.0%, memory 7.8%). Of the 1.83 M
branch misses per run, 94% are in NameSet::read and 86% at one branch, the tag compare of the
probe: with the slots half full, a letter passes half a slot of other names on average before
its own, and each such pass is a likely miss.
Dropped, against the code before them; ab.py on AC power, 41 interleaved runs, two rounds, and
perf stat, 20 interleaved runs:
- The letter as one AVX2 vector, from one 32-byte load and one AND, and posted with one
32-byte store, with its three words taken out of the vector for the hash: instructions -5.7%,
but cycles +1.4% (on battery power) and
ab.py+1.3% and +1.4%; with the group stored as one byte, +0.9% and +0.5%. Top-down: frontend latency 8.4 → 9.6 to 11.1% of the slots. Step 32’s letter posted right after its name went the same way. - One text path for every record, the loop over 64-byte blocks that 2% of the records take, which saves 18 lines (387 → 369): instructions +13.9%, cycles +5.0%.
- Non-temporal prefetches (on battery power,
perf statonly): of the input, cycles +4.7%; of the region table, +2.4%; of both, +7.2%. - Batches of 6 and 8 records instead of 4, on this step’s code, three rounds: 6 0.0% to +0.1%, 8 -0.1% to -0.7%. Batches of 3, before the byte store and the reference: +1.6% and +1.8%.
- The distinct names counted from the bits after the last round (not built): the marking’s
test and count are already one
btsand onesbbon the group’s count, and a pass over the bits would visit every set bit, 0.9 per letter, since 89.8% of the records add a pair. - The merge as vectors (not built): the compiler already adds the record’s first four fields to its group with one AVX2 add.
Step 37: a bounds check and a load fewer per record
Two changes in the record loop. Neither adds a line. Both came from reading the loop’s machine
code next to a perf record of its user-mode instructions over 40 runs, with each sample charged
to its line:
- The group’s index unchecked. The merge indexed
groupswith the group read fromby_id, and the compiler compared it with the length ofgroupsfirst, two instructions per record. The check can never fail, whatever the input: step 1 writes intoby_idonly the number of a code that occurs, which is belowgroup_count, the length ofgroups, every other byte stays 0, and an id past the table maps to 0. Alone: instructions -0.66%, cycles -0.80%. - The thread count as
sent.len(). A letter goes to the thread given by its hash times the thread count, shifted down by 32. The worker’s closure holdsthreadsby reference, so the multiply waited on two loads, one after the other: the reference from the stack, then the count through it.sentholds one mailbox position per thread, so its length is the same count, and the multiply now reads it from the stack in one load. On top of the first change: instructions -0.65%, cycles -0.47%.
On AC power, ab.py, 41 interleaved runs, four rounds, against step 36: medians 26.35, 26.50,
26.41 and 26.29 → 26.19, 26.30, 26.41 and 26.19 ms (-0.6%, -0.8%, 0.0% and -0.4%). Six earlier
rounds of the same machine code, built before the comments were written, measured -0.2% to
-1.0%. perf stat, 20 interleaved runs: instructions:u 1024.4 → 1011.1 M (-1.3%, 309 → 305 per
record), cycles:u 586.2 → 581.3 M (-0.8%). memory.peak, 15 alternating runs: medians 12.36 →
12.39 MiB. S 387 → 387. Correctness: the gate, 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give
the reference hashes; the 400 fuzz cases and the two long-name sets pass at the default thread
count, at 1, 3, 12, 37 and 64 threads, and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300
tiny seeds pass at 1, 2, 3, 5, 7, 12, 16, 23, 37 and 64 threads with 100-byte rounds; the six
files of edge cases match the reference at the default thread count, at 1 and 37 threads, and
with 100-byte rounds at 3 and 64; clippy reports no warnings.
The loop’s other bounds checks stay. Each guards a read at a stop found by the parse before it, and a malformed last record can put such a stop at the end of the input, where the read would run past the padding.
Dropped, against step 36 unless noted; ab.py on AC power, 41 interleaved runs, and perf stat,
20 interleaved runs:
- The name set’s tables as local slices in
NameSet::read, taken again after each insert, so that the probe would not load the slots’ address and length throughselffor every letter: instructions +1.1%, cycles +2.6%,ab.py+2.1% and +2.6%. - The group unchecked in the marking too, the distinct count after the barrier, which takes
one more line: instructions -1.0%, but cycles -0.6% and -0.8%, no better than the merge’s
change alone, and in three rounds of
ab.pywith both, +0.3%, -0.2% and +1.0% against it. - The id’s word read unchecked (
perf statonly): with every read ofnumberunchecked, which is not sound, instructions -1.85% but cycles -0.45%, against the merge’s change alone. Only the reads at a record’s start can be shown in bounds for any input. The slow amount parse also callsnumber, from stops that a malformed last record can put at the end of the input, and keeping its check takes more lines. - The letter made after the region id and the amount, on top of both changes: instructions -0.31%, cycles +0.42%.
Step 38: the last worker writes the output, with no runtime setup
Step 37’s workers returned their groups, and the main thread merged them, wrote the output and exited once every worker’s thread had ended. On an instrumented copy of step 35 (local, P-cores, µs after the fork, medians of 21 interleaved runs), the workers passed the last barrier at 23,520 and had all given back their runs by 24,007, but the last thread ended only at 24,773: a thread that ends unmaps its signal stack and has glibc drop its stack’s pages, each call takes the address space’s lock, and so the twelve ended one after another. The merge, the format and the write took 405 µs more, and the exit 646.
Now no worker returns. Each puts its groups in parts, and the last one to get there merges the
others into its own, writes the output and calls exit, while the others sleep in
thread::park until the exit ends them. Threads killed asleep cost the exit about 0.3 ms that
threads already ended did not (629 against 343 µs from the exit call to the wait’s return), less
than half of what ending them took. Under gdb on the E-cores (4 threads), a run makes 4 munmap
and 10 sigaltstack calls instead of 10 and 14. Since join never returns, its mailboxes and
region table are never freed either.
Each worker also gives back its name set’s entries, 6.4 MB in all at full scale, with
madvise(MADV_DONTNEED) on the whole pages inside them, after its run. The exit used to unmap
them on one thread: from the exit call to the wait’s return took 1,064 µs without this and 629
µs with it, while the twelve calls, in parallel, took about 127 µs. From the last barrier to the
wait’s return, the tail took 2,289 µs on step 35, 1,689 µs with the last worker writing, and
1,446 µs with the name sets given back too (with their slots, see below; 21 runs each). On step
36 it took 2,496 µs before and 1,541 µs after (25 runs). The name set itself is still never
freed (step 33).
ab.py against step 37, 41 interleaved runs, four rounds: medians 26.09, 26.26, 26.37 and 26.10
→ 25.66, 25.64, 25.69 and 25.57 ms (-1.6%, -2.4%, -2.6% and -2.0%). memory.peak does not move,
as every page goes back after the peak: in a user scope on the P-cores, 80 alternating runs,
medians 12.31 → 12.33 MiB, and the highest of 5 runs by resampling 12.79 → 12.68 MiB; in the
harness’s container on the E-cores (4 threads), 50 alternating runs, 10.52 → 10.48 MiB. S 387 →
391. Correctness: the gate, 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes;
the 400 fuzz cases and the two long-name sets pass at the default thread count, at 1, 3, 12, 37
and 64 threads, and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300 tiny seeds pass at 1, 2,
3, 5, 7, 12, 16, 23, 37 and 64 threads with 100-byte rounds; the six files of edge cases match the
reference at the default thread count, at 1 and 37 threads, and with 100-byte rounds at 3 and 64;
of the wide region sets, w2 gives the reference, and w0 and w1, with more than 255 countries,
stop with the error as step 37 does; clippy reports no warnings.
main is now C’s main, named with #[unsafe(no_mangle)] under #![no_main], so the setup
that the standard library runs before a Rust main does not run. That setup installs a handler
for stack overflows, and while it is installed, every spawned thread maps and protects the pages
of a signal stack of its own as it starts, two calls that take the address space’s lock for
writing while the main thread is still spawning. Under gdb on the E-cores (4 threads), a run
makes 22 mmap and 9 mprotect calls instead of 27 and 14, and sigaltstack is not linked at
all. std::env::args still works, because glibc hands the arguments to the standard library’s
initializer before main. A stack overflow now ends the process with SIGSEGV and no message, and
SIGPIPE keeps its default action, which a program that writes one file never meets. The binary
is 122 KiB smaller. ab.py against the change above alone, 41 interleaved runs, four rounds:
25.66, 25.64, 25.69 and 25.57 → 25.36, 25.46, 25.44 and 25.37 ms (-1.2%, -0.7%, -1.0% and
-0.8%), and against step 37 -2.8%, -3.0%, -3.5% and -2.8%. memory.peak: 12.33 → 12.23 MiB in the
user scope (80 runs; highest of 5, 12.68 → 12.73), 10.48 → 10.52 MiB in the container (50 runs).
S 391 → 393. The same checks pass, with the same results.
Dropped, against step 35 unless noted; instrumented timelines on the P-cores, medians of 21
interleaved runs (25 on step 36), or ab.py, 41 interleaved runs, four rounds:
- The name set freed after the run instead of its entries given back (on step 36):
ab.py26.51, 26.52, 26.53 and 26.49 ms against 25.80, 25.88, 25.81 and 25.88 ms, +0.67 ms.munmaptakes the address space’s lock for writing, so the workers’ calls ran one at a time. - The slots given back too, the set’s other table, 64 KiB per worker (on step 36): the tail 1,489 against 1,541 µs, 52 µs for three more lines.
- The region table and the mailboxes given back, each worker its share after one more barrier, with the threads still ending as before: the tail 1,817 against 2,289 µs, no better than the name sets alone, 1,810 µs. With the last worker writing, the region table alone (on step 36): 1,474 against 1,489 µs.
- The sleeping workers spinning instead (on step 36): the tail 1,491 against 1,489 µs.
- The main thread as worker 0, after it spawned the others (on step 36): the tail 1,509 against 1,489 µs.
- The sleeping workers ending their threads with a raw
exit(2): the standard library of Rust 1.99 then panics, “threads should not terminate unexpectedly”. - The join’s mailboxes and region table leaked when it returned, instead of freed: the tail 2,056 against 2,408 µs. The last worker’s exit now gives that with no line.
- The region table mapped in by worker 0 before its step 0, instead of by the main thread before the spawn: the last worker’s rounds started at 2,143 against 2,043 µs.
MADV_SEQUENTIALorMADV_RANDOMon the input mapping: the last worker’s rounds started at 2,116 and 2,113 against 2,043 µs, and the walls stayed within the noise.- The region table mapped in by the main thread after the spawn instead of before it, so
that its 0.2 ms would overlap the threads’ start (on step 36 with no runtime setup):
ab.py25.44, 25.55, 25.54 and 25.60 → 25.49, 25.66, 25.69 and 25.67 ms, for three more lines. - One malloc arena for all threads (
mallopt(M_ARENA_MAX, 1), on step 36 with no runtime setup): 30.00, 30.27, 30.23 and 30.21 ms, +4.7 ms. - glibc’s
M_MMAP_THRESHOLDleft at its default, two lines fewer (on this step): memory.peak 12.20 → 12.38 MiB (medians, 80 alternating runs in a user scope), and the highest of 5 runs 12.63 → 13.14 MiB by resampling.
Step 39: 23 instructions fewer per record
Eight changes in the record loop and the name set, none of which adds a line. They came, as step
37’s did, from reading the loop’s machine code next to a perf record of its user-mode
instructions over 40 runs, each sample charged to its line. Each count below is perf stat’s
instructions:u, 20 interleaved runs, on step 37’s code with none or some of the other changes,
against the same code without that change.
Step 37 kept the loop’s other bounds checks, since a malformed last record can put a stop of the
parse at the end of the input. Three of them, though, read near a position that an earlier
check or the parse has already bounded, well inside the pad’s 64 bytes, so they can never fail.
Each function now has that as the # Safety contract of its read, and each call says why it
holds:
- The name’s 24 bytes.
text_fieldshas just read the 64 bytes from the name’s field on, its first window, with a checked read, and the name starts there or one byte later, past its quote, soname_letter’s 24 bytes lie in that window. 4 instructions per record (-1.3%). - The region id’s and the amount’s 16 bytes.
region_amountreads from one past the comma that ends the note. A mask of commas finds only commas, and the 64 bytes of the pad are zeros, so that comma is a byte of the input, and the 16 bytes past it end inside the pad at the latest. 5 instructions per record (-1.6%). - The byte after the cents, the CR or the LF.
region_amountputs the dot at most 13 bytes past the comma’s next byte, andregion_amount_slowat most at the pad’s second byte, so the byte 3 past the dot lies in the pad at the latest. 3 instructions per record (-1.0%).
The check that stays is the window’s: a last record with no comma after its id puts the id’s stop on the pad’s first byte, and the window from the byte after it would end one byte past the pad.
Five smaller ones:
- A CR told from an LF by its lowest bit. CR is 0x0D and LF 0x0A, and the byte after the cents is one of them or, after the last record, the pad’s 0 (§2.1). One instruction per record (-0.33%).
- The region id’s length checked with one compare. The fast path took region ids of 1 to 7
digits as
comma.wrapping_sub(1) < 7. An empty region id, which §2.2 rules out, now takes it too and parses as 0, as it does in the slow path, socomma < 8is enough. One instruction per record (-0.34%). - The quotes counted with
bzhi. The quotes before a comma were counted asquotes & ((1 << i) - 1). The compiler does not know thatiis below 64, so it masked the count first;_bzhi_u64takes any count. 2 instructions per record (-0.63%). - A slot’s entry above its tag. A slot held its entry’s number in its low 24 bits and 8 bits of the name’s hash on top, so the probe masked it once for each. With the number on top, one shift takes it out and the tag compares as the low byte. 2.3 instructions per record (-0.77%).
- The marking’s group unchecked. After the barrier, the distinct count indexed
groupswith the group that the letter’s poster took fromby_id, which holds 0 or a number belowgroup_count, the length of every worker’sgroups, since all count the same codes. One instruction per record (-0.33%). Step 37 dropped this change, which then took one more line; with the word and the bit taken in onelet, it takes none.
Together, on AC power, ab.py, 41 interleaved runs, five rounds, against step 38: medians 25.64,
25.65, 25.60, 25.50 and 25.58 → 25.05, 25.07, 24.97, 24.93 and 25.06 ms (-2.3%, -2.3%, -2.5%,
-2.2% and -2.0%). perf stat, 20 interleaved runs: instructions:u 1014.4 → 936.8 M (-7.6%, 306
→ 282 per record), cycles:u 583.8 → 569.8 M (-2.4%). On step 37’s code the same changes took
1011.2 → 947.0 M instructions (-6.3%) and 582.6 → 567.7 M cycles (-2.6%), and in seven rounds of
ab.py against step 37, -1.7% to -2.7%. Cycles fall by less than instructions: many of the
instructions cut were a compare and a branch that never jumps, which the core fuses into one
operation. memory.peak, 40 alternating runs: medians 12.36 → 12.33 MiB. S 393 → 393.
Correctness: the gate, 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; the
400 fuzz cases and the two long-name sets pass at the default thread count, at 1, 3, 12, 37 and
64 threads, and with 100-byte rounds at 1, 2, 3, 12 and 64; the 300 tiny seeds pass at 1, 2, 3,
5, 7, 12, 16, 23, 37 and 64 threads with 100-byte rounds; the six files of edge cases match the
reference at the default thread count, at 1 and 37 threads, and with 100-byte rounds at 3 and 64;
of the wide region sets, w2 gives the reference, and w0 and w1, with more than 255 countries,
stop with the error as step 38 does; clippy reports no warnings.
Dropped, on step 37’s code; ab.py on AC power, 41 interleaved runs, and perf stat, 20
interleaved runs:
- The probe’s slot read unchecked: one instruction per record fewer (-0.32%), but cycles
+0.44%, and
ab.py+0.1% and +0.6% against step 37; on top of the CR’s bit, thebzhi, the slot’s layout and the marking’s group, +0.3%, +0.2% and +0.5% against them. - The letter posted before the region id and the amount are parsed, on top of those four: instructions -0.34%, cycles +2.3%. The letter made after them, which step 37 dropped too, again on top of those four: instructions +0.35%, cycles +0.63%.
- The shuffle controls indexed by
dot << 3 | comma, which oneleacould compute, instead ofcomma << 4 | dot: the compiler shifted and ORed all the same, instructions -0.00%, cycles +0.24%. As a table of 17 dots by 8 commas indexed with no mask, it added a bounds check. - The dot found by a shift past the byte after the comma, so that its range check would be one compare: instructions -0.02%.
Step 40: the field’s word read unchecked
number parses a field from the 8 bytes at its start, read as one word, and checked on every
call that they lie in data. They always do: every caller starts the word at most two bytes
past the input’s end, and the pad is 64 bytes. number is now an unsafe fn whose contract is
that the 8 bytes lie in data, and each of its six calls says why they do. The change adds no
line.
- The id at a record’s start, and the id 3 bytes on after a BOM. The record starts below its run’s end, which is at most the input’s length. The BOM test reads the record’s first byte unchecked for the same reason: with the word’s check gone, the compiler checked that byte instead, two instructions per record.
- The two fields of
region_amount_slow. The region id starts one past the note’s comma, at most at the input’s length, and the amount one or two bytes past the region id’s stop, which is at most the pad’s first byte or a comma of the input.region_amountandregion_amount_slownow both require that their start be at most the input’s length, which the record loop knows from the comma before it. - A row of the region table, which starts below the body’s end, and the last row’s id, one past an LF that lies before the pad.
On AC power, ab.py, 41 interleaved runs, seven rounds, against step 39: medians 25.01, 24.95,
25.08, 25.11, 25.09, 25.10 and 25.07 → 24.80, 24.74, 24.73, 24.84, 24.78, 24.83 and 24.77 ms
(-0.8%, -0.8%, -1.4%, -1.1%, -1.2%, -1.1% and -1.2%). perf stat, 20 interleaved runs:
instructions:u 936.6 → 911.0 M (-2.7%, 282 → 274 per record), cycles:u 566.4 → 560.7 M (-1.0%).
memory.peak, 40 alternating runs: medians 12.27 → 12.23 MiB. S 393 → 393. Correctness: the gate,
310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give the reference hashes; the 400 fuzz cases and the
two long-name sets pass at the default thread count, at 1, 3, 12, 37 and 64 threads, and with
100-byte rounds at 1, 2, 3, 12 and 64; the 300 tiny seeds pass at 1, 2, 3, 5, 7, 12, 16, 23, 37
and 64 threads with 100-byte rounds; the six files of edge cases match the reference at the
default thread count, at 1 and 37 threads, and with 100-byte rounds at 3 and 64; of the wide
region sets, w2 gives the reference, and w0 and w1 stop with the error as before; 73 inputs cut
short at every awkward place (inside the id, after one or two bytes of a BOM, inside a quoted
note, inside the region id and the amount, with and without a CR, and region tables cut short
in their last row) give the same exit status, panic message and output as step 39; clippy
reports no warnings.
Where step 39’s 282 instructions per record go, from perf record of instructions:u with
PEBS’s precise distribution (:ppp), 120 runs, one sample per 4,000,037 instructions, each
charged to its line of the record loop. With :pp instead, the samples piled up behind slow
instructions: the region table’s prefetch, one instruction per record, drew 10 per record.
| Part of the record loop | Instructions per record |
|---|---|
text_fields, with text_fields_slow (3.4) | 60.8 |
region_amount | 38.0 |
NameSet::read and NameSet::insert, the marking | 33.0 |
number for the id, and the BOM test | 31.7 |
name_letter, without its three crc32s | 22.0 |
merge of the record into its group | 18.6 |
| the batch: its stores, its loop, the group’s lookup and its byte in the letter | 17.8 |
| the letter’s four stores into its mailbox | 14.8 |
| the loop’s control, both prefetches and the line end | 11.8 |
| the post: the owner, the slot and its count | 8.8 |
no line in the line tables after inlining: the crc32s, reloads of spilled values | 23.8 |
| the rest: rounds, barrier, setup, tail | 1.0 |
Dropped, against step 39; ab.py on AC power, 41 interleaved runs, and perf stat, 20
interleaved runs:
- The empty name kept out of the exchange. At full scale 1.0% of the records have an empty name, whose letter is all zeros, so its hash and its owner are 0, and worker 0 marked about 11% more letters than the others. With no worker posting it, and a byte per group, shared and set once, to count it, +4 lines: six rounds from -0.5% to +0.2%, instructions +1.0%, cycles +0.0% and +0.3%. With the branch that sets the byte made cold: three rounds from -0.3% to +0.2%, instructions +0.9%, cycles +0.0%. Not posting it at all, which leaves it out of the counts, as the bound on what balancing worker 0 can gain: three rounds from -0.6% to +0.1%, instructions +0.2%, cycles +0.2%.
- A pad of 128 bytes, so that the 64-byte window of
text_fieldswould be read unchecked too: a last record cut short after a BOM puts the id’s stop on the pad’s third byte, and the window from the byte after it ends 67 bytes into the pad. Alone: instructions -1.46% (4 per record), cycles -0.17%, three rounds 0.0%, 0.0% and -0.3%. With this step’s change, against it: instructions -0.77%, cycles -0.02%, seven rounds from -0.2% to +0.2%.
The board’s run, run-d1b2c0ca269e (commit ca86ea9), drew 24.0 ms, a slow draw: step 39’s code drew 22.8 ms in its own run, and this step runs 0.8 to 1.4% faster locally. A second run of the same code, run-604f816aac75 (commit 0327cbc, which changed only track A), drew 22.76 ms, 12.5 MB and 80.5 points.
Step 41: a name known by its hash
Until step 40, a letter carried the name’s first 24 bytes, a CRC32 and the length, 32 bytes, and a longer name as its offsets in the file, and an owner’s entry for a name was a 64-byte cache line: that 32-byte key and 32 bytes of group bits. At full scale the ~100k entries took 6.4 MB, about half of memory.peak.
- The letter is a hash.
name_letterreads the name’s 32 bytes as two 16-byte blocks,aandb, masked to its length (names hold no NUL byte, §2.2, so the blocks are one to one with the name), and hashes them in three instructions,aesenc(aesenc(aesenc(a, b), KEY), KEY). The record’s group goes into the hash’s top byte. A name over 32 bytes, which no generated input has, takes the coldlong_letter. - One store per letter. The 16 bytes go to the mailbox in one store, where the two atomic stores took 7 more instructions per record.
- The entry is 40 bytes. A slot holds the entry’s number and 8 bits of the hash, so a probe loads an entry only when they match. The entry holds 64 more bits of the hash, the key, beside the 256 group bits. Two names are taken for one only if those 72 bits agree: with about 8,400 names per worker, a run merges two names with odds of about 1 in 10^13.
Built up on step 39’s code (perf stat, 20 interleaved runs, against step 39): the hash and the
40-byte entries, instructions -4.3%, cycles -3.0%; with the one store, -6.8% and -3.7%. Kept
apart, as an array of keys and an array of group bits, the marking took 21% more L1 misses and
the runs 0.6% longer; 48-byte entries ran slower than 40-byte ones. Four round keys instead of
one, with a and b passed through as many rounds, took five instructions and a table of nine
lines, and gained nothing for names that no adversary chose.
Local, against step 40 (ab.py, 41 interleaved runs on the P-cores, four rounds; the first three
with a browser busy on one P-core, so the minimums are the steadier figures): medians 25.63,
27.68, 24.22 and 24.81 → 24.69, 25.67, 23.10 and 23.68 ms (-3.7%, -7.3%, -4.6% and -4.6%),
minimums 24.17, 24.30, 23.87 and 24.32 → 22.92, 23.16, 22.69 and 23.22 ms (-5.2%, -4.7%, -4.9%
and -4.5%). perf stat: instructions:u 909.4 → 852.6 M (-6.3%, 274 → 257 per record).
memory.peak, 80 alternating runs: median 12.34 → 10.88 MiB, expected highest of five 12.91 →
11.06 MiB. S 393 → 381. Correctness: the gate, 310 pass, 0 fail; full seeds 1 to 7 and 10 to 12 give
the reference hashes; the fuzz and thread-count suite, 3,000 cases, and the 30 edge-case files
pass; of the wide region sets, w2 gives the reference, and w0 and w1 stop with the error as
before; clippy reports no warnings.
Step 42: 13 fewer lines
Seven of the cuts leave the machine code as it was (the .text section’s sha256 is step 41’s):
region_amountloads its window fromdatadirectly and returns themadd’s sum as it comes, with no temporaries; its two SAFETY comments are one.ALIGNsets each control byte with oneif/else, the table and its index in onelet.text_fields_slowandregion_amount_slowkeep#[cold]and drop#[inline(never)], aslong_letterdoes: LLVM keeps cold functions out of line either way.
Six change it, so they were timed:
- The per-round mailbox reads are one
(0..threads).for_each(…). - A mailbox publishes its end,
sent[to], instead of its count, so the reader slices up to it with no multiply and subtract. - The slot and the parsed count are bumped in one assignment.
parallel, used once, is written intojoin.
Local, against step 41 (ab.py, 41 interleaved runs on the P-cores): the six together, medians
23.59 and 23.67 → -0.21% and -0.30%, and in a third round 23.69 → 23.62 ms, minimums 23.30 →
23.02 ms. Each alone: from +0.04% to -1.10%. S 381 → 368. Gate: 310 pass, 0 fail; clippy reports
no warnings.
The board ran step 41’s code a second time in run-13fb3e0130ce (commit c9d5326, which changed only PERF.md): 21.49 ms, 11.4 MB and 81.65 points.
Step 43: no runs of late rounds, and rounds of 128 KiB
An instrumented copy of step 42 took a timestamp as each worker arrived at and left each barrier (local, P-cores, 21 runs; the machine now runs with turbo on, so a run takes about 14 ms instead of 23). The waits took 1.87 ms of each worker’s 11.6 ms of rounds, 16%, though in half the rounds the last worker arrived within 2 µs of the first. The rest came from about 20 rounds per run in which the last worker arrived 90 to 110 µs after the first, and in 18 of them that worker had slept at the barrier before: 2,000 spins last about 60 µs, a sleep of 50 µs may end 50 µs late with the default timer slack, and the CPU goes idle, so the sleeper left the barrier about 180 µs after it arrived, late for the next round, its waiters slept in turn, and the run went on for up to 20 rounds. About two rounds per run started one fresh, with a worker whose round took 140 µs instead of 40.
- Short sleeps.
mainsets the timer slack to 1 ns (PR_SET_TIMERSLACK, which the threads inherit), and a waiter that has spun 2,000 times sleeps in steps of 10 µs instead of 50. +1 line. - Rounds of 128 KiB. Step 16 found them flat against 64 KiB, with more memory: a round’s letters to one owner, about 180 of 32 bytes, took two pages of its mailbox. Since step 41 a letter is 16 bytes, so they fill 2.9 KB, part of one page as at 64 KiB. Alone, on step 42’s barrier, they were slower (15.23 against 14.40 ms, medians of 41 runs): each late round now costs more.
ab.py against step 42, 41 interleaved runs, medians / minimums: seed 1, 14.86 / 12.95 → 13.11 /
12.00 ms (-11.8%); seed 2, 14.20 / 12.99 → 13.26 / 12.16 ms (-6.6%); in the same way with the
tails printed, seed 1, 14.40 → 13.07 ms (-9.2%), and seed 3, 14.10 → 13.02 ms (-7.7%), p90 17.05 →
13.79 ms. With a busy loop of another program on CPU 5 (15 runs): 38.52 → 31.00 ms. memory.peak,
5 alternating runs: 9.9 to 10.5 MB for step 42 and 10.2 to 10.7 MB for this step; no allocation
changed. S 368 → 369. Correctness: the gate, 310 pass, 0 fail; full seeds 1, 2, 3, 7 and 12 give
the reference hashes, and seed 2 does on 1, 3 and 4 CPUs; clippy reports no warnings.
Dropped, against step 42, 41 interleaved runs unless noted:
- A longer spin,
SPINS30,000 (about 1 ms) instead of short sleeps: as fast in the medians (seed 1, 14.48 → 13.05 ms; seed 3, 14.33 → 13.47 ms; 10,000, 100,000 and 200,000 spins within 0.2 ms of it), and on the instrumented copy the waits fell from 1.87 to 0.76 ms per worker. But the tails grew: 3 runs in 61 took 47 to 96 ms, and with a busy loop on CPU 5, 172.9 ms against 38.5 ms. While the spinners hold every other CPU, the worker that shares its CPU is not moved. With rounds of 128 KiB on top, medians 13.14 and 13.10 ms, the same as this step.
Step 44: 3 fewer lines
S 369 → 366. Both cuts are in code that runs once per worker or once per round, not per record:
- Step 1 numbers the present country codes with
(present().zip(1..)).for_each(…)and takesgroup_countas1 + present().count(), instead of aforloop with a counter. The extra walk over the 17,576 code bits runs once per worker during setup. - A round’s mailbox ends are stored with one
(sent.iter().enumerate()).for_each(…).
Four other cuts came out longer after rustfmt (calls and chains over 60 characters are split
one argument per line): the money closure on one line, the two write!s of an output line as
one, the country-code closure inlined into its collect, and the rehash’s probe as a find.
ab.py, full seed 1, turbo off, 41 interleaved runs, medians / minimums, step 43 → step 44:
23.57 / 22.96 → 23.47 / 22.65 ms and 23.47 / 22.75 → 23.60 / 23.03 ms, the same within noise.
The gate passes (310 of 310).
On the same machine with turbo off, step 43 runs at 23.5 ms against step 42’s 23.62 ms before it: the 7 to 12% that step 43 measured with turbo on most likely came from idle states the board’s machine does not reach (its run drew 21.88 ms, step 42’s 21.86 and 22.25).
Step 45: hyperthreads that mark while their sibling parses, and 39 M fewer instructions
A profile of step 44 (P-cores, turbo off, 10 runs of perf record -e cycles:upp) put 24 to 26% of
the samples in NameSet::read, 43% of them on the compare of the entry’s key, which waits on the
entry’s load, and 5 to 14% on the barrier’s pause. The marking runs on all 12 threads at once
after each barrier, so both hyperthreads of a core waited on loads at the same time, and both
parsed at the same time, when the core’s ports are the limit (about 1.9 instructions per cycle
each).
- Marking beside a parse. The round loop runs once more than there are rounds, and in each
round a worker marks the letters of the round before, from the other half of the mailboxes:
before its parse if
sched_getcpu()is even, after it if odd. Both orders mark round r-1 between barriers r-1 and r, and nothing posts to that half until barrier r has passed, so the result is the same. CPUs 2k and 2k + 1 are the hyperthreads of one core here, so each core runs one marking next to one parse at the start and the end of each round. The parity is read once per round, so a worker that moves still marks each round once. +6 lines. - The text window unchecked.
byte_masktakes the 64 bytes as&[u8; 64], andtext_fieldsreads them without a bounds check, as anunsafe fn: the id’s stop is at most the pad’s first byte, or its fourth after a BOM, soPADgrows to 128 bytes and the window always fits.text_fields_slowkeeps the check for its further blocks. 16.9 M fewer instructions (4.8 per record). - The probe unchecked.
NameSet::readtakes the slot withget_unchecked, since the slots are never empty, and the entry too, since a slot’s number names an entry pushed before it. 13.0 M fewer instructions (3.7 per letter). - Min and max as branches. A record rarely sets a new min or max, so
mergestores each only when it changes. 9.1 M fewer instructions (2.6 per record), and two stores fewer.
perf stat -r 10, full seed 1: instructions:u 851.3 → 812.2 M for the last three, then 800.2 M
with the order of marking and parsing; the profile then has 24% in read and 5 to 10% in pause.
ab.py, turbo off, interleaved runs, medians / minimums, step 44 → step 45: full seed 1, 51
runs, 23.39 / 22.89 → 22.68 / 22.02 ms (-3.0%) and 23.43 / 22.85 → 22.52 / 22.08 ms (-3.9%);
full seed 2, 41 runs, 23.38 / 23.01 → 22.54 / 22.05 ms (-3.6%). The three unchecked reads and
the branches alone: 23.52 → 23.06 ms and 23.48 → 23.08 ms (-2.0%, -1.7%); the order of marking
on top of them: 23.04 → 22.74 ms and 23.08 → 22.82 ms (-1.3%, -1.1%). memory.peak, 5 alternating
runs: 10.3 to 10.6 MB for step 44 and 10.0 to 10.4 MB for this step. S 366 → 376. The gate passes
(310 of 310), full seeds 1 and 2 give the reference hashes, and clippy reports no warnings.
Step 46: the name set’s loop never calls out of it, and number on an SSE window
perf stat on step 45 counted 801 M instructions, and both hyperthreads of each core stay busy,
so the instruction count decides T (see “where step 45 stands” below). Two cuts, together:
readwithout a call in its loop.insertwas a call inside the marking loop, so after it the slots’ pointer, their length (for the mask) and the entries’ pointer could have changed, and the loop loaded all three again for every letter: 3 loads and adecper letter. Now a new name returns fromreadintoinsert, which adds it and callsreadagain on the letters from that one on; it finds its entry this time. Both calls are in tail position with at most six register arguments, so each is ajmpand the stack does not grow.insertreads the key and the tag from the letter itself,readtakes the letters as[AtomicU64; 2]pairs (mailslicesboxes), and it walks them as a slice,letters = &letters[1..], since anenumerateindex or a separate rest took two more instructions per letter and spilledgroups. A letter whose name is in its home slot runs 32 instructions instead of 35; each new name pays about 70 for the second entry and its probe, 100k times per run. +1 line.numberon an SSE window, as measured on step 45 below: 16 M fewer instructions, the same lines. Alone it was within noise (below); with the change above it holds.
perf stat -r 10, full seed 1, interleaved: instructions:u 800.6 to 802.0 M (step 45) → 797.1 to 799.4
M (the loop alone) → 773.7 to 775.1 M (both), branch misses 1.84 M throughout. ab.py, turbo off,
61 interleaved runs per round, medians / minimums, step 45 → step 46: full seed 1, 23.36 / 22.67
→ 23.07 / 22.21, 23.50 / 22.68 → 23.02 / 22.33, 23.24 / 22.53 → 23.10 / 22.24, 23.28 / 22.86 →
22.92 / 22.33 and 23.42 / 22.35 → 22.95 / 22.33 ms; full seed 2, 23.24 / 22.57 → 22.91 / 21.99,
23.80 / 22.76 → 23.55 / 22.59, 23.33 / 22.72 → 22.96 / 22.50, 24.06 / 22.60 → 24.83 / 22.52 (a
busy round, means 30.8 and 31.8 ms) and 23.45 / 22.76 → 22.95 / 22.25 ms. Nine of ten medians
and all ten minimums lower, typically by 1.5%. The loop alone: 23.30 → 23.19 and 23.30 → 23.15
ms; number alone: 23.30 → 23.20 and 23.30 → 23.29 ms (seed 1, same rounds). memory.peak, 3
alternating runs: 10.0 to 10.3 MB for step 45 and 10.1 to 10.5 MB for this step. S 376 → 377. The gate
passes (310 of 310), full seeds 1 and 2 give the reference hashes, and clippy reports no warnings.
Step 47: a name one slot past home found without a branch
At step 46, 87% of the 1.84 M branch misses per run were the probe’s tag compare in
NameSet::read, for a name that is not in its home slot. Names are drawn uniformly (spec §2.2),
so no placement can favour the frequent ones. With 8,400 names in 16,384 slots, as a worker holds
at full scale, a simulation of the table puts 74.6% of names in their home slot, 14.6% one past
it and 10.8% further on.
- Home and next in one read. The probe reads the home slot and the next as one
u64, andselect_unpredictabletakes the next when the home slot’s tag is not the name’s. If the chosen slot’s tag and its entry’s key match, that is the entry. Otherwise the probe loop runs from the home slot as before, so empty slots and inserts are handled where they were. The slots get one more, always empty, so the last slot has a next. Entry 0 holds no name, so a slot holds its entry’s index (no- 1) and an empty slot that is chosen leads to entry 0. Its key, 0, matches only a name with tag 0 and key 0, as two names collide, on 72 bits.readtakes the slots and the entries as slices first: throughselfthe compiler loaded both, and the slots’ length, again for every letter. +7 lines.
perf stat -r 10, full seed 1, interleaved, step 46 → step 47: branch misses 1.84 → 1.02 M,
instructions:u 774.6 → 778.3 M and 774.7 → 778.7 M, cycles:u 528.1 → 553.2 M and 531.4 → 562.2 M.
cycles:u rose while the wall time fell. One likely reason: it counts the barrier’s spins, which
grow when the marking ends sooner. ab.py, turbo off, interleaved, medians / minimums: full seed
1, 41 runs, 23.29 / 22.36 → 22.75 / 21.90 ms; 61 runs, 22.87 / 22.26 → 22.59 / 21.75, 22.89 /
22.10 → 22.69 / 22.16, 22.89 / 22.12 → 22.76 / 22.10 and 23.19 / 22.21 → 22.81 / 22.04 ms; full
seed 2, 61 runs, 22.99 / 22.36 → 22.67 / 21.92, 22.97 / 22.37 → 22.65 / 22.09, 23.17 / 22.38 →
22.99 / 21.68 and 23.17 / 22.43 → 22.93 / 22.16 ms. All nine medians are lower, by 0.6% to 2.3%
(about 1.2% typically), and eight of nine minimums. memory.peak, 5 alternating runs:
10.0 to 10.3 MB for step 46 and 9.8 to 10.5 MB for this step. S 377 → 384. The gate passes (310 of
310), full seeds 1 and 2 give the reference hashes, and clippy reports no warnings.
Step 48: the region table in one pass
A timeline of step 47 (P-cores, turbo off, an instrumented copy, 8 runs, from the start of
main): the workers start at 0.53 to 0.73 ms and the last at 0.84 to 1.17 ms, the last ends step 0
of the region table at 0.98 to 1.33 ms, the last ends step 1 at 1.27 to 1.94 ms and the first round
starts at 1.33 to 2.00 ms. Step 1 took 0.25 to 0.6 ms: two scans of the 17,576 code bits with an
atomic load each (present()), the second parse of the share’s rows and a barrier. After the
last round, the release of the input took 0.51 to 0.66 ms per worker, the entries 0.03 to 0.10 ms, and
the merge, format and write 0.2 ms.
- One step. Each worker parses its share of
regions.csvonce and writes each row’s group. A code’s group lives in a shared array of 17,576AtomicU8, 0 until the code’s first row is read; that row takes the lock, checks again and gives the code the next number. A share holds almost every code, and the workers start up to 0.6 ms apart, so the first worker numbers most codes and the others take the lock for a few. Groups are no longer in bytewise order, so the last worker walks the codes in index order (bytewise) to their groups for the output. Each worker keeps all 256 groups a byte can name, so both indexes into them (the merge and the marking) are checked by the type and need nounsafe. The lock is the one that collects the workers’ groups at the end. S 384 → 384.
perf stat -r 10, full seed 1, interleaved: instructions:u 775.2 → 769.6 M and 800.7 → 787.2 M
(the barrier’s spins vary). ab.py, turbo off, 61 interleaved runs per round, medians / minimums,
step 47 → step 48: full seed 1, 22.03 / 21.61 → 21.92 / 20.95 and 22.22 / 21.75 → 22.01 / 21.43
ms; full seed 2, 22.19 / 21.37 → 22.03 / 21.23 and 22.34 / 21.72 → 22.08 / 21.64 ms. Before the
lines were trimmed (the same code): seed 1, 22.31 / 21.84 → 22.19 / 21.15 and 22.31 / 21.72 →
21.95 / 21.57 ms; seed 2, 22.24 / 21.67 → 22.03 / 21.67 and 22.20 / 21.72 → 21.96 / 21.57 ms.
All eight medians lower, by 0.5% to 1.6% (about 1.0%). memory.peak, 5 alternating runs:
10.3 to 10.7 MB for step 47 and 10.2 to 10.6 MB for this step. The gate passes (310 of 310), full seeds
1 and 2 give the reference hashes, and clippy reports no warnings.
Step 49: 23 fewer lines
S 384 → 361, in code that runs once per worker, once per round or off the hot path:
region_rows, called once, is written into the worker, and the shares ofregions.csvcome from the closure that cutsrecords.csvinto runs: a row starts with a digit, so the first line after a cut that starts with a digit or a BOM is a row. Its code is onefold. -5.mallopt(M_MMAP_THRESHOLD)goes. It was there because the regions parse freed its lists and glibc then raised its threshold; nothing that large is freed now, and the name sets’ entries, the mailboxes and the region table are past glibc’s default 128 KiB either way. memory.peak, 20 alternating runs, medians 11.48 → 11.50 MB (in abashwrapper, so about 1 MB above the brief’s figure), andab.py22.03 / 22.09 / 22.09 / 22.13 → 21.99 / 22.02 / 21.93 / 22.26 ms. -2.map_filepanics with the error and the path instead of returning aResultthatmainunwrapped, so the mapping’s check is one line. -2.ENTRY, used once, goes (its doc moves toNameSet::slots). The rehash finds its empty slot withfind. The round’s mailbox ends are stored with onefor_eachover0..threads. The output line takes its key throughescape_asciiinstead of a separateextend_from_slice.valuesshuffles in two statements instead of one split over four lines,prefix_xoris twounsafeexpressions,numbertakes its length withtrailing_ones, and its loop for long fields is apositionand afold.region_amounttests the sign inline, andtext_fields_slowtakes the parity at a block’s start from its count of quotes so far. -14.too_many_linesis allowed inCargo.toml:joinwent past clippy’s 100 lines.
perf stat -r 10, full seed 1, interleaved: instructions:u 762.2, 762.6, 763.2 and 762.1 M at
step 48, 761.9 and 763.7 M here. ab.py, turbo off, 61 interleaved runs per round, medians /
minimums, step 48 → step 49: full seed 1, 21.99 / 21.51 → 21.93 / 21.42, 22.01 / 21.58 → 22.00 /
21.46 and 22.01 / 21.49 → 21.96 / 21.46 ms; full seed 2, 22.08 / 21.60 → 22.13 / 21.64 and
22.02 / 21.50 → 22.01 / 21.57 ms, the same within noise. memory.peak, 20 alternating runs,
medians 11.56 → 11.54 MB. The gate passes (310 of 310), and clippy reports no warnings.
Measured and not kept:
- The two tails of
text_fieldsas one: the slow path returned the two ends with their quote counts and the fast path’s tail computed the lengths for both. -3 lines, but instructions:u 762.0 → 794.9 M (+4.3%). number’s loop for long fields kept as it was, with the other cuts: the worker’s function is 7,702 bytes against 8,837 with thefold, which LLVM unrolls, yetab.pymeasured 22.11, 22.13 and 22.12 ms against 22.01, 21.99 and 22.04 ms with it (61 runs, interleaved with step 48 at 22.03, 21.92 and 22.00 ms): the layout of the hot loop moved.
Step 50: groups built on the heap, and main as worker 0
What is live at the peak, the end of the last round (step 49’s code, full seed 1, P-cores, an
instrumented copy that reads /proc/self/pagemap and memory.stat there; 4 KiB pages):
| Block | Pages | MB |
|---|---|---|
| name-set entries, 12 × ~8,400 names × 40 bytes | 988 | 4.05 |
| mailbox pages, 2 × 144 mailboxes × 1 page | 288 | 1.18 |
| region table, 1 byte per id | 245 | 1.00 |
| name-set slots, 12 × 16,385 × 4 bytes | 204 | 0.84 |
| thread stacks, 12 × 6 pages | 72 | 0.29 |
| groups, 12 × 16 KiB | 48 | 0.20 |
heap, binary, main’s stack, group_of | ~15 | 0.06 |
| page tables (memory.stat) | 0.72 | |
| kernel stacks, 13 threads | 0.21 | |
| slab | 0.13 | |
| memory.current less all of the above | 540 to 610 | 2.2 to 2.5 |
The last row is memcg’s per-CPU charge stock: a CPU that charges a page takes 64 at a time
from the counter and keeps the rest for its next charges, so each of the 12 CPUs holds 0 to 63
pages that memory.peak counts and no page uses (plus the bash wrapper’s own, in this
measurement). Of the input’s page tables, about 97 pages are the 202 MB mapping.
- Groups on the heap. The worker’s frame was 16.9 KB:
Box::new([EMPTY; 256])built the 16 KiB of groups on the stack and copied them into the box, and the stack probes touched every page of the frame, which stayed mapped.vec![EMPTY; 256]builds them in place; the frame is 664 bytes and each stack touches 2 pages instead of 6. anon 7.96 → 7.77 MB in the same dump. +1 line. - Main as worker 0.
mainspawned all 12 workers and slept in the scope. Now it spawns 11 and runs worker 0: one spawn fewer before the first round and one thread fewer. +3 lines.
Both alone, ab.py, 61 interleaved runs, medians: groups on the heap 22.03 → 22.02, 22.04 →
22.02 and 22.08 → 22.00 ms; main as worker 0 on top of it 22.16 → 21.96, 22.28 → 22.33, 22.04 →
21.94, 22.11 → 21.89, 22.07 → 21.89, 22.03 → 21.91 ms, and on full seed 2 22.14 → 22.05 ms.
Together, step 49 → step 50, medians / minimums: full seed 1, 22.08 / 21.58 → 21.88 / 21.53,
22.04 / 21.44 → 21.98 / 21.51 and 22.05 / 21.66 → 21.93 / 21.56 ms; full seed 2, 22.00 / 21.53 →
21.95 / 21.57 and 22.16 / 21.58 → 21.95 / 21.57 ms (-0.6%). instructions:u 761.9 and 762.5 M →
762.2 and 763.0 M. memory.peak, the brief’s systemd-run, 8 alternating runs: 10.2 to 10.6 MiB
(median 10.4) → 9.9 to 10.7 MiB (median 10.15); in the bash wrapper, 20 runs, medians 11.52 →
11.46 MB. S 361 → 365. The gate passes (310 of 310), and clippy reports no warnings.
Costed and not built, for memory:
- 36-byte entries, a 32-bit key: the rehash places a slot by its entry’s key, so the key must hold the home bits, and 32 bits of key with the 8-bit tag leave 40 bits to tell two names apart, about 1 in 2,600 runs merging two names at full scale. -0.4 MB.
- Mailboxes packed below a page: a mailbox holds the worst case, every record of a round to one owner, so they are a page or more apart and each touches a page per half. With 8-byte letters (56 bits of hash) and 2 KiB boxes, with an overflow area for the worst case, the mailboxes would take 144 pages instead of 288, -0.59 MB, for a test per post and about 20 lines.
- The input’s page tables freed during the rounds by unmapping each 2 MB the worker has
parsed: about -0.3 MB, but
munmaptakes the address space’s lock for writing, which the workers’ unmaps then take one at a time (step 38 measured 0.7 ms for the name sets’), and the input would need one mapping per run. - The charge stock: memcg drains it only under reclaim, at a limit or when another cgroup charges on that CPU, none of which the program controls.
Costed and not built, for speed: the id and the region’s amount in one 256-bit chain
(vinserti128 of the two windows, then one subtract, shuffle and multiply-add chain for both).
It saves 3 to 5 of the ~205 instructions a record takes (3.72 M records, 762 M instructions),
for 10 to 15 lines and a slow path that must undo the pairing when either field is long or
carries the byte-order mark. At 0.011 points a line it must win more than 1.2% of T to pay,
and at most 2.5% of instructions go.
Step 51: one worker fewer than the CPUs
Two of eleven board runs of steps 48 to 50 took 47 to 49 ms instead of about 20. Locally, with a busy loop pinned to one of the twelve CPUs, step 50 takes 57.6 ms (median of 31, full seed 1) instead of 21.9: the worker on that CPU gets half of it, every one of the 129 rounds waits for that worker at the barrier, and the scheduler leaves it where it is because it is cache-hot. The same busy loop costs A, B and D 17 to 28%, since they meet at a barrier only a few times.
The final score is the mean of the middle three of five runs, and a batch is re-run only when they spread by more than 50 ms, which a 47 ms run does not reach. At two slow runs in eleven, about one batch in five would hold two, and the mean of the middle three would then be about 29 ms, 4 points less. With one worker fewer, a busy CPU leaves a spare one:
| Binary (full seed 1, 31 runs each) | No busy CPU, median | One busy CPU, median |
|---|---|---|
| Step 50, 12 workers | 21.9 ms (2 of 31 runs above 1.5x) | 57.6 ms |
| Step 51, 11 workers | 24.0 ms (1 of 31) | 23.7 ms |
ab.py, 41 interleaved runs on full seed 1, step 50 against step 51: medians 22.63 against 23.95
ms (+5.8%, about 0.6 points), means 33.79 against 24.68 ms, because step 50 had slow runs under the
machine’s own load. The cost is paid on every run. It buys out a one-in-five chance of about 4
points.
Step 52: 8 fewer lines
S 365 → 357 (Rust 359 → 352, the Dockerfile 6 → 5), in code outside the record loop or with the same machine code inside it:
- The build stage runs
RUN --mount=type=bind,target=/src cd /src && cargo build …, as tracks A and D do, instead ofWORKDIR /srcand then the mount. Both stages stay. The image’s/app/joinhas the local build’s sha256. -1. - The three
uselines are two:arch::x86_64::*joins thestd::{…}list, andDuration, used once, is writtenstd::time::Durationthere. -1. - Both
prctlcalls set their option to 1, so they are onemapover[41, 29], with one comment for the two options. -1. BOMandSPINS, each used in one place, are written there: the record loop tests for0xEFand parses the id again 3 bytes on, and the barrier sleeps after 2,000 spins, its counter typedusizeasSPINSmade it. The comments keep what their docs said. -2.halfandoddare set in one statement, and so arenamesandsent. -2.text_fieldsnames the offsets of its two commasnameandnote, astext_fields_slowdoes, which makes the returned tuple short enough to take the name’s range directly. -1.
Every cut but one leaves the machine code as it was. names and sent in one statement change
the worker’s code (9,250 → 9,328 bytes) but not what it runs: with one worker (taskset -c 2),
instructions:u 753,563,908 at step 51 and 753,563,915 here. perf stat -r 20 on the P-cores,
interleaved: instructions:u 765.1, 765.1 and 765.1 M → 765.2, 765.0 and 765.1 M; cycles:u 481.5,
480.7 and 481.5 M → 481.7, 480.1 and 480.5 M. ab.py, turbo off, 61 interleaved runs, medians /
minimums, step 51 → step 52: full seed 1, 23.03 / 22.49 → 23.02 / 22.55 and 23.08 / 22.28 →
23.04 / 22.54 ms; full seed 2, 23.04 / 22.67 → 23.09 / 22.62 and 23.07 / 22.66 → 23.11 / 22.73 ms.
memory.peak, the brief’s systemd-run, 5 alternating runs: medians 9.7 → 9.7 MiB on full seeds 1
and 3; no allocation changed. The gate passes (310 of 310), and clippy reports no warnings.
Measured and not kept:
- Each output line as one
format!, the lines collected into aString: -2 lines, but with one worker 753.56 → 754.12 M instructions (+551 k per run, about 2,300 per line, since eachformat!starts with no capacity and grows), all of it in the last worker’s tail after the rounds. text_fieldsreturning the note’s comma, the caller adding 1: -1 line, instructions:u 765.4 → 768.5 M (+0.4%).region_amount_slowwritten intoregion_amount’s branch behindstd::hint::cold_path(): -3 lines, but the worker grew from 9.3 to 10.3 KB and instructions:u went 765.4 → 778.4 M (+1.7%).long_letterwritten intoname_letter, not built:name_letterwould then call itself, and LLVM does not inline a recursive function, here into the record loop.- Left for clarity:
NameSet::newwritten into the worker (-2),mainandjoinas one function (-2), theALIGNloop’si += 1folded into a tuple assignment (-1).
Step 53: a worker on every CPU again
Step 51 gave up a worker so that a CPU taken by another program would not halve one worker and every round. That load came from the shared live board and from this machine’s other programs. The board README says final scoring is “five runs on the hidden holdout seed, with the box to itself”, one run at a time, and the highest of the five is dropped. Two slow runs in one batch of five on an idle box are unlikely, while the spare CPU costs every run.
ab.py, 61 interleaved runs, step 52 against step 53, medians / minimums: full seed 12, 23.00 /
22.68 → 21.44 / 21.01 ms (-6.8%); full seed 1, 22.97 / 22.40 → 21.32 / 20.70 ms (-7.2%), about
+0.75 points. One run of step 53 on seed 12 was slow under this machine’s own load (mean 26.90
ms), the kind of run final scoring drops. S 357 → 357. Gate: 310 pass, 0 fail.
Step 54: 9 fewer lines
S 357 → 348 (Rust 352 → 343), with the record loop’s machine code unchanged:
NameSet::readtests whether a slot’s entry is the name’s in one closure,hit, which the home slot’s test and the probe loop share; the loop breaks with the entry’s index, and one uncheckedget_unchecked_mutafter it takes the entry. The slots’ mask is set once with the slices, and the tag and the group are bytes 14 and 15 ofhigh.to_le_bytes(), as the docs number them. -3. The function’s machine code has the same 78 instructions, oneshrmoved.name_lettertakes the length in alet len @ 0..=32 = … elsethat callslong_letter, where anifreturned:cmp $0x21; jaeforcmp $0x20; ja. -1.text_fields_slowXORs the parity of the quotes before a block into bit 0 of its quote mask, which carries it into every bit of the prefix XOR, instead of XORing all ones in after it: one instruction fewer on that cold path. -1.text_fieldscallsbefore(name)andbefore(note)in the lengths, without naming the counts; the compiler computes each once, as before. -1.- The batch writes a record’s group through
top[1].as_ptr(), byte 7 of the letter’s second word, instead of casting the letter’s reference to a byte pointer first. Same machine code. -1. - The mailboxes are one
Box::leaksplit byas_chunks, with nolettersbinding: nothing is freed anyway. -1. mainreads the data directory inside the closure that maps the files (env::argsimported in place offs::write, now written in full at its one use). -1.
Every function has the same instruction count as at step 53, compared function by function with
objdump, except main (191 → 337 instructions: args is parsed twice, once per run) and
text_fields_slow (122 → 121); the worker’s 1,892 differ only in register choices. perf stat -r 5, interleaved, instructions:u, step 53 → step 54: full seed 1, 762.28,
762.27 and 762.19 M → 762.10, 761.95 and 761.93 M; full seed 2, 762.37, 762.51 and 762.16 M →
762.00, 762.06 and 764.38 M (that run also took 531.7 M cycles against 485 to 493 M for the others, a
busy CPU). cycles:u 488.6, 488.1 and 486.3 M → 487.0, 483.6 and 483.6 M on seed 1. ab.py, turbo
off, 21 interleaved runs, medians / minimums: full seed 1, 21.89 / 21.39 → 21.59 / 21.26 and 21.84 /
21.43 → 22.05 / 21.37 ms; full seed 2, 21.94 / 21.36 → 21.93 / 21.37 ms, the same within noise. No
allocation changed. The gate passes (310 of 310), and clippy reports no warnings.
On the board: step 54’s first run, run-83d1167e1735, came on a slow box, and the next push replaced its queued rerun. The C code has not changed since, so every later C run measures step 54: run-dc3871163ade (pushed with 0491b7f) took 19.42 ms, 11.36 MB, 83.07 points, and run-a69fa3d057dc (47858fc) 19.63 ms. One later run, run-e75aab520ba9 (61a6ab7), took 53.37 ms while A, B and D in the same push ran at their usual times (16.87, 93.65 and 121.77 ms): the busy CPU of step 51, which final scoring, with the box to itself, should not see (step 53).
Measured and not kept:
text_fieldswith the note’s comma fromlet note @ 0..64 = … else: -1 line, but the test becametzcnt; cmp $0x40; jaeafter theblsrwhose flags thejeused, one instruction more per record.- The posted letter’s slot read through
sent’s reference at each use, withoutslot: -1 line, but the worker grew from 1,892 to 1,907 instructions (the slot is loaded again after the letter’s store). - The input’s prefetch in one statement: rustfmt splits it over three lines (104 columns).
- Left for clarity:
format_outputwritten into the last worker’s tail (-3),map_fileas a closure inmain(-1), the rehash without its filter of empty slots, which would place each as entry 0 into an empty slot, a no-op (-1).
Experiments that did not stay
-
One malloc arena for all threads (after step 53; local, seed 1):
mallopt(M_ARENA_MAX, 1)at startup./proc/<pid>/smapsat the peak showed twelve 132 KiB arena heaps, one per worker, at 84 KiB resident each, 1 MB in all, beside a 116 KiB main heap. With one arena the same pages were touched in the main heap, so the 84 KiB are the workers’ own data and not the arenas’ slack: memory.peak over five alternatingsystemd-runs, medians 10.3 → 10.3 MB.ab.py, 41 interleaved runs: 21.36 → 24.09 ms (+12.8%), the workers’ allocations serialized on one lock. Not kept. -
Rounds cut into chunks that the workers claim, with 12 workers again (after step 51; local, P-cores, turbo off). Each run’s 128 KiB share of a round became 8 chunks of 16 KiB, claimed from per-run atomic counters, own run first; a worker took another run’s chunk only while each mailbox it writes to had room for one more chunk. With a busy loop pinned to CPU 3 the kernel put two of our workers on one other CPU, and a 60 µs barrier spin starved the second one, so a worker that shared its CPU with another worker marked first, yielded after each chunk and yielded instead of spinning.
ab.py, 61 runs, medians: 21.76 and 22.16 ms on seeds 1 and 2, against 21.78 and 22.12 for step 50 and 23.49 and 23.78 for step 51. With the busy CPU: 25.3 ms against 22.1 quiet (+14.5%), where step 51 stays flat and step 50 takes 57.3. It costs 31 lines and 0.6 MB, so it nets about +0.16 points on a quiet run and about +0.04 once busy runs are counted. A worker that the scheduler leaves on the same CPU as another program gets no special handling, a placement that never happened locally but would bring back step 50’s slowdown. Chunks with the spinning barrier took 48.5 to 50.0 ms under the busy CPU; 4 or 16 chunks per round 28.2 and 28.9 against 25.5 for 8; handing a name set to the worker on the same CPU 25.5, 1% slower quiet, and one wrong hand-off in 20 runs. -
Where step 50 stands (local, P-cores, turbo off, an instrumented copy with a timestamp at each phase of each worker, 21 runs, medians, ms from the harness’s spawn of the process).
mainstarts at 1.2 to 1.7 ms (an empty static program: 1.6 ms) andjoin0.09 ms later. The first spawn returns 0.35 ms afterjoinstarts (the region table’sMADV_POPULATE_WRITEand the cuts), the last 0.73 ms after; the workers start over 0.25 to 0.3 ms, and the first round starts when the last of them has parsed its share of the rows, 0.95 to 1.0 ms afterjoinstarts. The 129 rounds take 18.2 ms: per worker 13.1 ms of parse, 3.9 ms of marking and 0.9 to 1.0 ms at the barriers; in half the rounds the arrivals spread over less than 5 µs, and the barrier lets everyone go within 0.3 µs of the last arrival. Then the release, 0.53 to 0.6 ms, the entries 0.07 ms, the merge 0.04, the format 0.13 and the write 0.04 ms. The process is gone 0.7 ms after the write, where an empty static program exits in 0.18 ms; an empty program with 11 parked threads takes 0.42 ms, and one that maps and touches the input and gives it back withMADV_DONTNEED0.20 ms. In the kernel profile (cycles:k, 10 runs),madviseis 20% of kernel cycles, the barrier’s sleeps 15% and the exit 0.7%. -
The region rows in shares taken in turn (on step 50’s code): 128 shares of
regions.csv, each worker taking the next from an atomic counter and cutting its share itself, so that the workers that start first parse more of the rows and the last to start finds them done. With the 96 cuts made bymainbefore the spawns, its page faults onregions.csvmade the spawns 0.1 ms slower and ate the gain. The instrumented copy put the first round 1.005 → 0.866 ms afterjoinstarts.ab.py, 61 interleaved runs, medians: seed 1, 21.95 → 21.83, 21.96 → 21.87 and 21.96 → 21.83 ms; seed 2, 22.06 → 21.98, 22.04 → 21.97 and 21.99 → 21.95 ms; two more sets of six rounds, three- and four-way, -0.49% and -0.31%. About -0.4% for +3 lines (S 365 → 368), worth +0.01 points at most. 96 or 48 shares: the same within noise. The gate passes (310 of 310). -
Workers that end their own thread with the
exitsyscall instead of parking, so the last worker’s exit kills no thread (on step 50’s code): the time from the write to the end fell 0.70 → 0.62 ms in the instrumented copy, butab.py, six rounds of 61 runs on seeds 1 and 2, medians averaged 22.04 ms for step 50 and 22.06 ms for this. +2 lines. -
The input given back in shares that all workers take, so that the last worker’s merge, format and write (0.22 ms) overlap the others giving back its run: giving back pages that another core faulted in is much slower, and the last share was given back 1.64 ms after the last round against 0.6 ms. The merge and format also slowed, 0.17 → 0.28 ms, beside the siblings’
madvise. -
A long spin at the first barrier only (50 ×
SPINS), so that the workers that start first do not sleep through the last arrival:ab.py, six rounds of 61 runs on seeds 1 and 2, 22.01 → 22.05 ms (medians averaged). -
preadinto a small buffer instead of the mapping, costed with a test program (12 threads on the P-cores, each streaming its twelfth ofrecords.csv, 5 runs): through the mapping 5.1 ms of faults and reads plus 0.6 to 0.7 ms ofMADV_DONTNEED, throughpreadinto a 16 to 128 KiB buffer 5.7 to 6.0 ms with nothing to give back. A wash, and the buffers would add 0.2 to 1.5 MB of memory. -
The input mapped in up front (local, turbo off, on step 47’s code): each worker called
madvise(MADV_POPULATE_READ)on its run before the region table, so that the rounds would not fault. Page faults 4,724 → 1,654, but cycles:k 59.0 → 63.5 M andab.py, 41 interleaved runs, medians 22.11 → 27.23 ms (+23%): the populate is slower per page than the faults it replaces, and it delays the first round. -
Where step 47 stands (P-cores, turbo off,
perf record -e instructions:uppandcycles:k, an instrumented copy for the rounds). Per record: about 150 instructions of parse and post (id 21,text_fields44, the hash 14,region_amount36, the post, the batch and the loop about 35), 28 of merge, and 33 per letter inNameSet::readfor a name at home; 775 M in all. cycles:k is 10% of all cycles: 55% of it the input’s page faults (filemap_map_pages,next_uptodate_folio), about 1.1 ms per worker inside the rounds, and 18% the release after them. In the rounds a worker works 95% of the span on average and the busiest 97%, so the barriers cost about 3% of jitter and 1.5% for the owner of the empty name, which gets 12% more letters. Costed and not built: the marking four letters at a time withvpgatherqqfor the slot pairs and the keys, about 8 instructions fewer per letter (a third of the groups of four hold a name past home + 1), for about 35 lines; the id’s value andregion_amountfrom one 256-bit shuffle and multiply-add chain, about 5 fewer per record; a third set of mailboxes, so a worker can run a round ahead, +0.58 MB for at most the 3% of jitter. -
Other ways to make the not-home case cheaper, costed before step 47 (simulation of 8,400 names in 16,384 slots, as one worker at full scale; none built):
- Robin Hood insertion: 64.0% at home, 24.6% one past it and 11.4% further on, against linear probing’s 74.6%, 14.6% and 10.8%. That is more names off home, and no fewer beyond the next slot.
- Aligned buckets of two slots, with overflow into the next bucket: 12.7% leave the home bucket, against 10.8% beyond home + 1 for the unaligned pair of step 47.
- A “displaced” bit in the home slot: whether a name is home stays as unpredictable as before (a quarter are not), so the bit only moves the missed branch.
- Starting the probe one slot past home when the home slot’s tag differs, branch-free, with
no separate hit path: skipping a home slot that is empty makes it linear probing from home
- 1, with the same misses, and testing that the home slot is taken costs 7 to 8 instructions per letter.
- A dense tag array matched 16 slots at a time: at least 16 KB more per worker beside the 32-bit indexes. Step 32’s eight-slot AVX2 compare already cost 32 M instructions for no gain.
-
The record’s sums as one vector in the batch (local, turbo off, on step 46’s loop): the batch held
[1, id, cents, name_len]as one__m256ifrom_mm256_set_epi64x, so the merge adds it with onevpaddqfrom memory and no vector built from four loads. Instructions 797.3 → 794.1 M only: the vector is now built at the parse, as two halves that the compiler stores with two 16-byte stores, and the merge’s 32-byte load cannot be forwarded from them (ld_blocks.store_forward3.5 k → 1.02 M per run). As eighti64in the batch, stored one by one, the same forwarding fails, and it loses the knowledge that word 5 is 0. -
The probe’s tag compared first, with an unused entry 0 (local, turbo off, on step 46’s code): a slot holds its entry’s index, entry 0 is a placeholder with key 0, and the probe tests the tag and the key before the empty slot, which drops a
jmp, anaddand a move from a hit. 764.2 against 773.7 M instructions, but branch misses 1.84 → 1.89 M andab.py, 61 interleaved runs, medians: 23.10 → 23.12, 22.92 → 22.96 and 22.96 → 23.10 ms. +1 line. -
Prefetching ahead in
NameSet::read(local, turbo off, on step 44’s code), now that the entry’s load holds 43% of its samples: at letter i, the slot of letter i + 2k prefetched and the entry of the slot of letter i + k (its first probe) prefetched, k = 4, 8 or 16, with the key’s line or the entry’s first.ab.py, 25 interleaved runs, medians: 23.37 → 23.74, 23.78, 23.91 and 23.85 ms. For k = 8: L1 misses 11.38 → 6.63 M, but instructions 851.4 → 928.5 M (22 per letter, the bounds checks of the reads ahead) and cycles 537.4 → 552.6 M. The entry prefetch alone, 6 letters ahead: 23.45 → 23.48 ms (31 runs). Step 9’s stage 4 found the same with 64-byte entries. -
The id’s digits summed without parsing them (local, turbo off, on step 45’s unchecked reads and branches): the id’s word, shifted so its last digit is the top byte, went into the batch, and the merge added its eight bytes, widened by
vpmovzxbd, into four more words of the group, as eight 32-bit sums of the digits at each place, joined intoid_sumonly for the output. That skips the id’s three multiplies. Instructions 812.2 → 809.0 M only, since the batch, the 96-byte groups and the slow path’s value took back most of them, and cycles 520.8 → 532.4 M and 521.9 → 528.3 M (perf stat -r 10, interleaved). -
The letter kept in a vector register (local, turbo off, on step 45’s code):
name_letterreturned the__m128i, the owner came from_mm_extract_epi32, and the store took the register, where the[u64; 2]went through the stack. 800.6 → 793.6 M instructions, butab.py, 51 interleaved runs, twice: 22.56 → 22.74 ms and 22.59 → 22.89 ms. +2 lines. -
Only the slot read unchecked in the probe, with the entry’s bounds check kept (one line fewer): 793.6 → 803.2 M instructions on the build above.
-
Where step 45 stands (P-cores, turbo off,
perf stat -M TopdownL1/L2, 10 runs): retiring 47%, core bound 22%, branch mispredicts 10%, fetch latency 10%, memory bound 6%. Of the 1.84 M branch misses, 87% are the probe’s tag compare inNameSet::read(a name not in its home slot, at a load of 0.51), and in the record loop the most cycle samples sit on the region byte’s prefetch, which waits on the region id’s multiply-add chain. -
The name sets’ slots at a quarter load (local, turbo off, on step 45’s code): twice the slots, 32,768 per worker at full scale. Branch misses 1.84 → 0.81 M, instructions 800.7 → 792.4 M, cycles 522.9 → 520.6 M and 526.5 → 517.8 M (
perf stat -r 10, interleaved), but memory.peak 9.9 to 10.2 → 10.6 to 10.9 MB (4 alternating runs): +0.7 MB costs about 0.25 points, which 1% of T does not pay for. -
numberon an SSE window (local, turbo off, on step 45’s code; kept in step 46 with the name set’s loop): the id, and every other fieldnumberreads, parsed asregion_amountparses the region id, a compare with/, its mask’s first zero for the length, and thepshufband multiply-adds of step 35 shared withregion_amount, instead of three multiplies of one word. The same lines (S 376), 800.8 → 784.5 M instructions, and the gate passes, butab.pyon a busy machine (other programs on the P-cores, means up to 33 ms), interleaved, medians: seed 1, 23.43 → 23.28, 23.07 → 23.05 (51 runs) and 23.15 → 22.97 ms (61 runs); seed 2, 23.35 → 23.54 ms (61 runs). Within noise, probably because the vector compare andvpmovmskbput the id’s comma a few cycles further along the record’s chain, and the multiply-adds share their ports with the text masks and the hash. As a separateidfunction beside the SWARnumber: 14 more lines for the same instructions. -
A structural index of the records (local, on step 32’s code), to break the chain between records: each record’s start waits on the id’s comma, the name’s and the note’s closing quotes, the region id, the sign, the amount’s dot and the CR test, about 80 cycles. Two shapes, both with the reference hashes on full seeds 1 and 2 and the 300 tiny seeds, and both slower:
- Two stages per 4 KiB of a round, after simdjson. AVX2 compares of each 64 bytes with
",,and LF, the bytes inside quotes as the prefix XOR of the quote mask (one PCLMULQDQ against all ones, carried from block to block), and every comma and LF outside them written to a buffer, eight positions at a time with no branch per position. The record loop then took five positions per record, so no record waited on the one before.ab.py, 40 interleaved runs, two rounds, medians / minimums 32.73 / 32.15 → 37.02 / 36.20 ms and 32.99 / 32.09 → 37.04 / 36.00 ms (+12 to 13%).perf stat -r 10on the P-cores, twice: instructions 1.414 → 1.941 G, IPC per thread 1.75 to 1.87 → 2.15 to 2.20, branch misses 2.87 → 1.93 M. The record loop was not tuned (each field’s quotes were counted by a loop), but the index alone took about 90 instructions per 64-byte block, about 85 per record. - Each record’s end from one compare: step 32’s parser, plus one 32-byte compare with LF right after the note, which gives the next record’s start, so the region id, the sign, the amount and the CR test leave the chain; the amount’s dot stays the fallback when no LF lies in those 32 bytes. 33.10 / 32.35 → 33.78 / 33.17 ms and 33.18 / 31.80 → 34.12 / 33.13 ms (+2.1 to 2.8%); instructions 1.416 → 1.450 G, 10 more per record; IPC per thread 1.82 → 1.80; branch misses 2.87 → 2.92 M.
- Without hyperthreads, 6 threads on CPUs 0, 2, …, 10 and 30 interleaved runs, both win: 45.99 / 44.19 ms for step 32, 45.00 / 42.76 ms for the two stages and 43.70 / 41.59 ms for the compare. A thread alone does wait on the chain, but with 12 threads its sibling fills those cycles, two threads at 1.75 to 1.87 instructions per cycle each, so the instruction count decides T.
- The full per-record window, masks over the 128 bytes from each record’s start with the
k-th comma or LF taken by
pdep, was not built: by an estimate from its compares, mask moves and 128-bit bit walks it runs 20 to 30 more instructions per record than step 32, more than the compare that already lost. On full seed 1, 41% of records are longer than 64 bytes and 0.06% longer than 96. A 64-byte mask misses the note’s closing quote for 11.2% of records when it starts at the record and for 2.2% when it starts at the name, as step 28’s does. The region id, the amount and the terminator never take more than 17 bytes.
- Two stages per 4 KiB of a round, after simdjson. AVX2 compares of each 64 bytes with
-
48-byte name-set entries (local, on step 32’s code): the key’s words for names of up to 15 bytes and the 32 bytes of group bits in 48 bytes, with longer names in a side list. M fell on every seed (10 seeds × 11 rounds, per-seed medians -0.33 to -1.02 MB, mean -0.69 MB), but
ab.pywent from 32.88 / 32.04 to 35.28 / 34.47 ms (median / minimum, +7.3%), with instructions 1,415 → 1,512 M, branch misses 2.87 → 3.44 M and L1 misses 11.2 → 13.1 M. A 48-byte stride puts half the entries across two cache lines. Step 32’s 64-byte entries moved 16 bytes off their alignment, so that every entry crosses two lines, cost the same 1.8 M extra L1 misses and +2.9% T with fewer instructions, so most of the loss is the layout itself. -
Eight slots probed at once (local, on step 32’s code): the tags of eight slots compared with one AVX2 compare and a
tzcnt. Branch misses fell from 2.87 to 1.34 to 1.40 M, but no variant saved cycles. Unaligned groups with a mirrored tail measured 32.95 → 32.69 ms with 32 M more instructions and 1.3 M more L1 misses. Aligned groups measured 33.07 → 33.10 ms, and with the hit’s entry taken from the register, cycles went 736.3 → 735.8 M. Peeking at a pair of slots withselect_unpredictablecut branch misses to 2.14 M and cost 2.6% more cycles. The mark loop’s mispredicts are partly hidden by the hyperthread sibling, so removing them gains less than their count suggests. -
Loops on 64-byte boundaries (
-C llvm-args=-align-loops=64, as track B builds; local, on step 32’s code): no gain.ab.py, 40 interleaved runs, two rounds, medians / minimums 33.01 / 32.02 → 33.00 / 31.73 ms and 33.03 / 31.96 → 33.09 / 31.85 ms. The output hash is unchanged. -
sent[to]read once per record (local, on step 32’s code): the four atomic stores of a letter make the compiler reloadsent[to]five times, each with a bounds check. Reading it into a local first measured slower: medians 33.01 → 33.37 and 33.03 → 33.89 ms (ab.py, 40 interleaved runs, two rounds). Step 34 reads it once after all, where on top of its other changes it cut cycles:u by 1.9%. -
PGO (local, turbo off, on step 27’s code): a profile from three runs on each of full seeds 2 to 4, passed as
-C profile-use, with every function matching it.ab.py, 40 interleaved runs, medians / minimums: 36.35 / 35.39 → 37.71 / 36.69 ms and 36.27 / 35.64 → 37.39 / 36.79 ms on seed 1; 37.38 / 36.22 → 38.55 / 37.47 ms and 37.14 / 36.35 → 38.39 / 37.31 ms on seed 10, which it was not trained on.perf stat -r 5: instructions:u the same, 1.535 G; cycles:u 0.841 → 0.875 G. -
The empty name counted by its posters (local, on step 25’s code). Every record with an empty name posts its letter to one owner, which then gets 11% more letters than the others (306k against 273 to 277k at full scale) and marks for 0.4 to 0.5 ms longer. Each poster instead kept one bit per country for the empty name, ORed together at the end. Not posting those letters measured the same, 37.33 against 37.16 ms (
ab.py, 40 interleaved runs, medians), and keeping the bits in the batch loop, with or without a branch, cost 2.2 to 2.3 ms through the loop’s register allocation. -
The name slots written at allocation (
[0].repeat(n)instead ofvec![0; n], local, turbo off, on step 17), after track B found that a first load from a calloc’d page maps the shared zero page and the store after it interrupts every core:ab.py, 40 interleaved runs, medians 40.16 → 40.18 ms on seed 1 and 39.74 → 39.80 ms on seed 2; page faults 6,350 → 6,351, kernel cycles 64.8 → 62.9 to 64.2 M. The slots do not fault that way here. -
Batched table lookups (local only): each thread parsed 32 records, then loaded every record’s region entry and hash slot, then found every name’s entry, so the cache misses within a batch overlap instead of following one another.
- E-cores, three alternating runs: cycles:u 1.95 to 2.00 → 1.70 to 1.73 G, task-clock 1129 to 1163 → 987 to 1010 ms, elapsed 0.324 to 0.334 → 0.292 to 0.297 s, instructions:u 2.66 → 2.93 G. S 412 → 448.
- P-cores,
perf stat -r 10, interleaved: task-clock 1073/1067/1075 → 1089/1076/1086 ms, elapsed 125/115/128 → 119/121/123 ms. No gain: on a P-core the hyperthread sibling already runs while one thread waits on a miss. Reverted. - Variants on E-cores: separate intern and OR steps 1.711 to 1.762 G (the fused form was equal or
slightly faster), explicit
prefetcht01.745 to 1.777 G, and batches of 16 or 64 within noise of 32.
-
Prefetching the entry as well as loading the slot early (local only, P-cores,
perf stat -r 10, interleaved, on top of step 5). In one variant, a prefetch of the entry was issued as soon as the slot’s value arrived. In the other, a one-record pipeline marked each record one record late and prefetched its entry in between. They measured 1044 to 1055 ms and 1035 to 1053 ms of task-clock, against 1036 to 1068 ms for the early slot load alone (step 7) and 1145 to 1185 ms for step 5. Neither was kept. -
Prefetching entries a few letters ahead while marking (local only, step 9’s stage 4, medians of 11 interleaved runs): 4, 8 and 16 letters ahead measured 64.17, 63.39 and 64.46 ms, against 64.18 ms without.
-
A region table indexed by rank (local only, on stage 5 before the byte-wide table): a bitset of the ids present plus a running count, so the group array holds only the 200k regions. 65.65 and 67.35 ms against 63.82 and 64.51 ms in two sessions, for 13.99 to 14.45 MiB against 15.70 to 15.74 MiB. The byte-wide table with
malloptreached 13.9 to 14.1 MiB at no cost in time (stage 5). -
Slots at three-quarters load instead of half (local only, on the rank-table build): 69.09 against 65.65 ms, for 11.53 to 12.46 MiB against 13.99 to 14.11 MiB.
-
Pinning each worker to the i-th CPU it may run on, with
sched_setaffinity(local only, on stage 5 before the byte-wide table): 63.37 against 63.67 ms over 21 runs, and 63.94 against 64.17 ms over 15. Letting hyperthread siblings mark in alternate phases on top of that: 63.44 ms in the second session. Both are within that build’s spread across sessions, 63.4 to 64.5 ms. -
A longer spin before parking, 20,000 spins instead of 2,000: 59.71 against 59.44 ms.
-
One name table shared by all parsers, with 4-byte letters (local, on step 35’s code). Each parser looked its record’s name up in one lock-free table of 262,144 slots, each an id plus one and 6 bits of the hash, with a 32-byte key per id. A key was written before a
ReleaseCAS put its id in a slot, and lookups read the slots withAcquire. A new name’s id was its owner’s next local index, from one atomic counter per owner, times the thread count plus the owner. A letter was then 4 bytes, the local index and the group, and each owner kept a row of 256 bits per name it owns, about 270 KB per owner.ab.py, 41 interleaved runs, two rounds, medians / minimums: 26.83 / 26.26 → 37.53 / 36.52 ms and 27.21 / 26.33 → 38.00 / 36.58 ms (+40%). With each name’s slot prefetched as soon as its hash was known and probed after the region id and the amount, as step 7 did, in a second session: 26.60 / 25.81 → 35.92 / 35.43 ms and 26.58 / 25.91 → 35.92 / 35.19 ms (+35%). Rounds of 512 KiB, which 4-byte letters allow at one mailbox page each: 35.87 to 36.06 ms.perf stat, 15 interleaved runs: instructions 1055.3 → 1078.9 M (+2.2%), cycles 601.7 → 867.6 M (+44%), L2 misses 2.52 → 7.36 M. Without the marking, the lookup and its letter alone ran 408 M cycles more than step 35 with no name work at all, where all of step 35’s letters and marking cost 228 M. In a profile of one run, a third of the cycles sat on two loads: the key’s (25% of the samples) and the slot’s (11%).- The whole table, 1 MB of slots and 3.2 MB of keys, is every core’s working set, while a P-core’s L2 holds 1.25 MB and the two owners on a core take 1.2 MB of step 35’s name sets. Step 35’s 32-byte letters cost bandwidth, but they stream through the mailboxes in order; the shared table costs two random loads per record that miss L2. Both run about 1.75 instructions per cycle, so even with every miss hidden, 2.2% more instructions could not have made it faster.
- memory.peak, 12 alternating runs: medians 12.58 → 13.21 MiB; S 387 → 427, untrimmed. The measured build’s table did not grow, so it was checked on full seeds 1 to 7 and 10 to 12, which give the reference hashes; a build that sizes the table from an upper bound passes the gate (310 pass, 0 fail).
-
The region table indexed by rank, again (local, turbo off, on step 39’s code), for memory: the 1 MB array of one group byte per region id became a 16-byte entry per 64 ids, the bits of the ids in the table and the count of table ids below them, and the groups of the 200,000 rows in id order, 0.45 MB at full scale. In step 0 each share’s rows set their bits with a locked OR and the shares counted their rows, and in step 1 each row’s group went to its number among all rows. A record’s group is the one at its entry’s count plus the set bits below its own, so the merge waits on a second load that depends on the first, after a
bzhiand apopcnt, and only the first load can be prefetched.ab.py, 41 interleaved runs, three rounds, medians: 24.92, 24.90 and 24.85 → 26.80, 26.76 and 26.80 ms (+7.5% to +7.8%). Unchecked, with the ids past the table clamped onto an empty last entry: 26.73, 26.67 and 26.77 ms (+7.1% to +7.7%);perf stat, 10 interleaved runs, instructions:u 936.8 → 995.7 M, cycles:u 570.5 → 630.1 M. With the groups’ index masked to their first 1 KB, so that the second load always hits L1 (a wrong output, for timing only): 25.79, 25.84 and 25.82 ms (+3.5% to +3.9%). About half the cost is that load’s misses and half the longer chain into the merge.- The group computed where the region’s byte was prefetched, and carried in the batch: 28.91 against 24.95 ms (+16%). The first load then misses with nothing to overlap it.
- Building the table moved the first round 0.06 ms later: 1.29 → 1.35 ms from the start of
join, medians of 41 runs. - memory.peak, 80 alternating runs: medians 12.28 → 11.76 MiB, highest of five 12.69 → 12.31 MiB (expected), with the groups’ 200 KB mapped in by main, as step 33 does for the byte-wide table. Main cannot know the row count before the workers count the rows, so the build measured took full seed 1’s as given. With each worker mapping in the groups of its own rows instead: 12.91 and 13.15 MiB, 0.6 MiB above step 39.
- S 387 → 420, untrimmed. At 0.345 points per MB and 0.108 per 1% of T, the 0.4 to 0.5 MB saved is worth about +0.16 points and +7% of T about -0.8. Even the masked build’s +3.5% would lose 0.38.
-
The byte-wide table mapped in by the first worker instead of by main (local, turbo off, on step 39’s code), so that main would start the threads 0.25 ms sooner, while that worker mapped in the 1 MB as the others started:
ab.py, 41 interleaved runs, medians 24.86 → 25.00 ms; memory.peak, 40 alternating runs, medians 12.18 → 12.36 MiB, highest of five 12.61 → 12.96 MiB (expected). -
Main maps in the region table after it starts the workers (local, turbo off, on step 41’s code), so that the 0.2 ms of
MADV_POPULATE_WRITEoverlaps the spawns:parallelinlined intojoinas athread::scopethat spawns the workers and then makes the call, with no change in lines. Main began spawning 0.20 ms sooner and the first worker started at 0.33 instead of 0.55 ms, but the last still started at 0.875 ms: each spawn took about 45 µs instead of 27 µs, and the first round began at 1.314 against 1.306 ms (instrumented copies, medians of 31 runs).ab.py, 41 interleaved runs: 23.37 → 23.33 ms. On step 42’s code, wherejoinalready spawns the workers in athread::scope, the call moved after the spawns: 23.57 → 23.73 ms. -
The workers started as a tree, each thread handing the upper half of its numbers to a new thread, as track A’s
fan_outdoes (local, turbo off, on step 41’s code): the last worker started at 0.963 against 0.938 ms and the first round at 1.429 against 1.353 ms;ab.py, 41 interleaved runs, 23.37 → 23.93 ms (+2.4%). -
The workers that finish first spin until the exit instead of parking (local, turbo off, on step 41’s code), so that their CPUs are awake when the exit kills their threads:
ab.py, 41 interleaved runs, 23.37 → 23.35 ms; the output was written at 21.33 against 21.27 ms. -
Memory charged ahead per CPU, measured after step 54 (local, not built). The kernel charges a cgroup for anonymous and kernel pages in batches of 64 pages per CPU, and memory.peak counts the part of each batch not yet used. A test program in which threads, each on a CPU of its own, touch pages and then wait at a barrier (memory.peak in a fresh scope, 5 runs, KiB): one thread touching 1,536 pages, 7,364 to 7,952; twelve threads touching 128 each, the same 6 MiB, 9,660 to 10,440; twelve threads touching one page each, 4,516 to 4,808, against 1,992 to 2,704 touching none. On step 54, sampling the cgroup’s memory.stat during the run (6 runs): peak 10.13 to 10.62 MiB, of which anonymous 6.80 to 7.08 MiB (name sets about 4.6, mailbox pages 1.1, the region table 0.95), kernel 0.66 to 0.82 MiB (page tables 0.35 to 0.50), and about 2.4 MiB charged ahead on the twelve CPUs. memory.current rises in steps of 0.25 MiB, one batch, and what a CPU holds ahead is what is left of its last batch, so it depends on how many pages that CPU charged, modulo 64. Variants on step 54’s code, seed 1 (peaks over 4 to 8 runs;
ab.pymedians, 31 or 41 runs):- Workers on stacks that main maps in (
pthread_create), whose pages 3, 6 or 12 of them map in during the region step, so that the others never fault a page: peaks 8.52, 8.52 and 9.41 to 9.52 MiB; times +5.2% and +5.5% (seeds 1, 2), +3.4% and +1.6%; S 348 → 422. - The same with the standard library’s threads: 10.05 to 10.54 MiB, +5.9%.
- Main making each worker’s name set, groups and posting ends, before the spawn: 8.52 to 9.38 MiB, +3.2% and +3.8%; during the region step: 8.52 to 8.77 MiB, +3.4%. Three workers making them: 8.77 to 9.61 MiB, +2.5%. Each worker mapping in its own pages first: 10.31 to 10.52 MiB. These peaks repeat run after run because each CPU’s page count does, but moving pages from one CPU to another moves its leftover either way, and a holdout seed with other counts would move it again. Averaged over that, only CPUs that charge nothing save, about 0.125 MiB each, against 2.5 to 5.5% of time. Not kept.
- Workers on stacks that main maps in (
Profile notes
- Knockouts on v1 (E-cores, cycles:u, a noisier run with v1 at 3.08 G): no name table 1.02 G, no name compare 2.16 G, no bitset OR 3.19 G (no gain), no region lookup 2.63 G. The name table cost about two thirds of all cycles, which is what step 2 went after.
- Knockouts after step 2 (E-cores, cycles:u): full 1.97 G, no name table 1.06 G, no region lookup 1.72 G, scan only 1.00 G.
- Phase timeline after step 2 (P-cores, 12 threads, instrumented copy): regions parse 0 to 11.0 ms on one thread; quote pre-pass 11.5 to 17.1 ms, about 5.5 ms per thread; workers 17.9 ms to about 104 ms, 85.1 to 86.8 ms each, so the chunks are balanced; merge about 1 ms; distinct counting 105.3 to 114.2 ms on one thread; format and write 0.6 ms. About 20 ms of the 115 ms runs on one thread.
- Setup timeline at step 39 (P-cores, 12 threads, turbo off, instrumented copy, medians of 21
runs, from the start of
join): main’s allocations and the region table’s 1 MB mapped in take 0.25 ms; the first worker starts at 0.47 ms and the last at 0.79 ms, in an order that does not follow the spawns, which points at idle CPUs waking up; step 0 of the region table ends at 0.61 to 0.92 ms; the workers that waited longest had gone to sleep and leave that barrier up to 0.12 ms after the last arrival; the second barrier passes at 1.22 ms. About 5% of T passes before the first round. - Setup and tail at step 41 (P-cores, 12 threads, turbo off, instrumented copy, medians of 31
runs, from the start of
main):joinstarts at 0.09 ms and spawns the workers at 0.34 ms, after the region table’s 1 MB is mapped in; the workers start at 0.55 to 0.87 ms and end step 0 of the region table at 0.69 to 1.00 ms; the first round starts at 1.31 ms. The last round ends at 20.53 ms, the workers have given back their pages at 20.97 to 21.05 ms, and the last one merges in 0.04 ms, formats in 0.15 ms and has written the output at 21.27 ms.ab.pymeasures 23.4 ms, against 1.6 ms for an empty C program, so about 0.5 ms passes between the write and the exit, and beforemain. Whether main spawns early, late or as a tree, the last worker starts at 0.87 to 0.96 ms.
Track D: Traverse
For each of 2,000 queries (s, t), print the length of the shortest directed path from s to t
in a weighted road graph of 1.7 million nodes and 5 million edges, or -1 when there isn’t one.
The clock covers everything: reading the files, building the graph, the searches and the output.
| Reference | Mine | |
|---|---|---|
| Time, full dataset, seed 1 | 72.69 s | 118.4 ms |
| Peak memory | 893 MB | 65.7 MB |
| Code lines | 43 | 424 |
| Board points | 0 | 73.6 |
About 610 times the reference’s speed. Step 5 in PERF.md is a good one to start with: packing each edge into 4 bytes dropped the peak from 125.2 to 83.9 MB.
Approach
flowchart LR
G["graph.txt<br/>5M shuffled edges, mapped"] --> B["parallel counting sort<br/>3 passes, no atomics"]
B --> F["forward CSR<br/>4-byte edges"]
B --> V["reverse CSR<br/>4-byte edges"]
Q["queries.txt"] --> A["12 workers<br/>next query from an atomic counter"]
F --> A
V --> A
A --> BD["bidirectional Dijkstra<br/>bucket queue, lazy deletion"]
BD --> O["distances.txt<br/>in input order"]
- There are two compressed graphs. One CSR groups every edge by its tail for the search from
s, and a second groups them by head for the search fromt, so either direction is one contiguous slice per node. - An edge is four bytes, with the neighbour in the low bits and the weight in the bits above it (21 and 11 at full scale). Nearly every road weight fits, and the rest go in a small side map. That halves both CSRs to 40 MB, so a search streams half the bytes and does half the page walks.
- The build is a parallel counting sort in three passes, with one thread per chunk of lines and
no atomics. The first pass counts each chunk’s edges per block of 2,048 node ids, the second
writes every edge into the run of the final array that belongs to its chunk and block, and the
third sorts each block by a 2-byte place value. A block fits in L2. There’s no comparison sort
and no per-edge allocation, and the only big buffers are the CSRs and one
u16place per edge. The build also faults its own arrays in with one write per 2 MB, so each huge page is first touched by a single thread instead of four at once. - Bidirectional Dijkstra grows one disc from
sand one fromtand stops soon after they meet. Two discs of half the radius cover about half the area of one full disc, and that’s the biggest single gain over the reference. A target with no in-edges empties the backward frontier in one step, where a forward search would settle the whole graph. - Each side keeps its frontier in a bucket queue with lazy deletion and its tentative distances in a small hash map, so a search pays only for the nodes it touches.
- Workers take the next unanswered query from a shared counter and each writes into its own
slot.
mainprints the slots in input order, so the output never depends on scheduling.
Dependencies
None here either, just the standard library.
cd track-d && cargo +1.99.1 build --release --offline
D’s .cargo/config.toml sets nothing beyond target-cpu=alderlake, so unlike the other three
it isn’t statically linked.
With another 24 hours
The CSR alone is 40 MB and the memory cap is 17.9 MB, so the graph can’t shrink much further without a different layout, and the search already has a bucket queue with lazy deletion and a two-step prefetch. What’s left is the build, about 27 ms, and the queries themselves, which use 53% of the CPU and whose cost you can’t tell from the query text. I’d run two experiments: split the query batch by expected cost so the 12 workers finish together instead of draining one long search at the end, and see whether the build’s first pass can drop its 2-byte place array when only the forward direction needs sorting. One idea I already measured and threw out was relabeling node ids in BFS order. The searches got 9 ms faster, but computing the order cost 80 ms and permuting the graph another 52 ms.
Track D: performance log
Every kept step names its board run. A number marked local is from my laptop (i7-13620H, turbo off), comparing two versions run side by side; experiments that didn’t stay are under the step they were tried after.
| Reference (step 0) | Final code (step 20), two board runs | |
|---|---|---|
| T | 72.69 s | 118.4 ms (run-4e0f7e6bd2df), 121.8 ms (run-56ed132a3ad9) |
| M | 893 MB | 65.7 MB, 65.8 MB |
| S (lines) | 43 | 424 |
| Points | 0 | 73.6, 73.3 |
| Step | Change | Run ID | T (s) | M (MB) | Points |
|---|---|---|---|---|---|
| 0 | The reference, unchanged | 72.69 | 893 | 0 | |
| 1 | Rust v1: forward and reverse CSR built by a counting sort with atomic adds, and a bidirectional Dijkstra per query on 12 threads (475265e) | run-3d72cc2b20e3 | 0.438 | 141 | 58.2 |
| 2 | Counting sort with no atomics (482dcb3), then a prefetch of the next node’s edges (c13e637), two steps deep (599190a) | run-97e259c08579 | 0.1889 | 128.2 | 66.7 |
| 3 | Numbers parsed eight bytes at a time (85568b4) | run-49af01c44df1 | 0.1665 | 125.8 | 68.0 |
| 4 | Heap entries ordered by one packed 128-bit key (542bc46) | run-05e531e8754c | 0.1565 | 125.2 | 68.6 |
| 5 | Edges packed into 4 bytes and read through a 32-byte copy, and glibc’s mmap threshold fixed at 64 KiB (680f4ad) | run-74c555d4ba4f | 0.1551 | 83.9 | 70.2 |
| 6 | The build’s arrays faulted in before pass 2, one write per 2 MB on half the threads (3d3e358; measured together with step 7) | run-bb1fd514f3b2 | 0.1279 | 81.4 | 71.6 |
| 7 | Each search’s binary heap replaced by a bucket queue: a ring of 4,096 one-unit buckets found through a bitmap, with a small heap for keys past the ring (fc4ed14) | run-bb1fd514f3b2 | 0.1279 | 81.4 | 71.6 |
| 8 | The query code shortened by 24 lines at the same speed: answer reuses on_threads, and the queue’s helpers are folded together | run-966433fb4d85 | 0.1264 | 84.0 | 71.8 |
| 9 | Each node’s edge range kept in 2 bytes instead of a 4-byte offset, in groups of 4 nodes, and pass 3 run one direction at a time with its index faulted in first | run-ee72c614f94f | 0.1297 | 75.5 | 71.8 |
| 10 | Label distances aligned to 4 bytes, so a label table entry takes 12 bytes instead of 16 | run-37fab0938045 | 0.1280 | 69.4 | 72.3 |
| 11 | Each queue’s top kept between steps; a step recomputes only its own side’s | run-37fab0938045 | 0.1280 | 69.4 | 72.3 |
| 12 | Pass 2’s runs kept as two slice iterators instead of their zip: 32 bytes a run instead of 48 | run-0581a96cbf3c | 0.1259 | 70.7 | 72.4 |
| 13 | Labels as u32 distances, with the rare longer ones behind a u32::MAX in a second map | run-954b4981ddcb | 0.1255 | 68.1 | 72.7 |
| 14 | 11 fewer lines with the same machine code: the single-item use lines in one, the mmap and mallopt constants written at their one call each with their names in a comment, the file descriptor passed straight to mmap, and two pairs of variables declared together | run-954b4981ddcb | 0.1255 | 68.1 | 72.7 |
| 15 | 1 fewer line with the same machine code: sort’s counters and its running sum declared together | run-5194056b1310 | 0.1244 | 68.4 | 72.7 |
| 16 | Queue::push forced inline, so a relaxation no longer pays for a call: 1.8% fewer instructions | run-fc6e22635c4b | 0.1221 | 67.7 | 73.0 |
| 17 | Pass 3 gives back the places of sorted blocks as it goes: the threads take the blocks in turn, and the 2 MB pages below the slowest one’s progress are dropped with madvise | run-d253110190f5 | 0.1276 | 66.0 | 72.6 |
| 18 | 30 fewer lines at the same speed: the Dockerfile without WORKDIR, one parser for edge and query lines, the runs cut with split_off_mut, the prefetches through one helper that takes an Option, and smaller cuts | run-e464a45452b1 | 0.1244 | 65.9 | 73.1 |
| 19 | The query threads that run out of queries drop graph.txt’s pages from the page tables, so the exit no longer unmaps them on one thread | run-f3c4ed0faa3c | 0.1246 | 65.6 | 73.1 |
| 20 | The build’s serial parts shortened: split_runs hands out the runs as they are asked for instead of collecting them, and the heavy-edge maps hash with NodeHash instead of SipHash | run-3416bb90eca1 | 0.1221 | 64.9 | 73.3 |
Local numbers are for full seed 1 unless a seed is named. “P-cores” means CPUs 0 to 11 of an
i7-13620H (its six P-cores and their hyperthreads), with all 12 threads and turbo off. Each figure
is perf stat -r 5, and variants were interleaved over three rounds. Peak memory is memory.peak of a
systemd-run scope on CPUs 0 to 11, with the inputs already in the page cache. A single board run is
noisy for this track: v1 scored 380, 438 and 500 ms, and step 3’s code scored 166.5 ms here and
165.2 ms in run-321ee44c222c. So each step below says which local numbers back it.
Step 2a: a counting sort with no atomics (482dcb3)
v1 counted degrees with one atomic add per edge and direction, then gave out slots with another.
Each add hit a random line of a 14 MB cursor array. On x86 a locked add also waits for every
store before it, so the scatter ran at one memory miss at a time per thread. The profile had
fetch_add at 26.7% of all CPU time, about 80% of the build. v1 also zeroed 80 MB of edge slots on
one thread before the scatter.
Now each thread counts its chunk’s edges per block of 2,048 node ids in private counters. A prefix
sum gives every chunk its own run of slots in every block, so the second pass writes with plain
stores. A third pass counting-sorts each block (about 47 KB, so it stays in L2) by node. Offsets
became u32, and the edge arrays come zeroed from the kernel instead of being cleared.
- P-cores: elapsed 394 to 410 → 289 to 296 ms, task-clock 4.34 to 4.45 → 3.25 to 3.33 s, cycles 10.1 to 10.4 → 7.4 to 7.6 G.
- Build phase on P-cores: about 60 ms after the change (21 + 31 + 8 ms for the three passes).
- Peak memory: 139.7 to 142.2 → 126.0 to 129.9 MB, from the narrower offsets. S 217 → 291.
Step 2b: prefetch the next node’s edges (c13e637)
After this change the queries were 80% of the run, and two dependent cache misses dominated each
settled node: its offsets entry, then its edge row, both at random spots in big arrays. The edge
row load alone was 22% of all samples and the offsets read 10%. The node settled next is usually the
one on top of the heap, so step now starts loading that node’s edges before it relaxes the
current node’s, which hides the wait behind that work.
- P-cores: elapsed 289 to 291 → 202 to 207 ms, task-clock 3.26 → 2.26 to 2.27 s, cycles 7.45 → 5.06 to 5.07 G.
- Peak memory unchanged. S 291 → 300.
Step 2c: two steps deep (599190a)
With the edge rows prefetched, the biggest stall became the offsets read for that prefetch (17.5%
of samples). The node after next is usually one of the heap root’s two children, so step also
prefetches their offsets entries. One step later the top’s offsets are already in cache.
- P-cores: elapsed 202 to 204 → 188 to 190 ms, task-clock 2.26 to 2.27 → 2.11 s, cycles 5.06 to 5.08 → 4.70 G.
- Seed 2: 204 → 194 ms. Seed 3: 218 → 198 ms.
- Peak memory unchanged. S 300 → 306.
Step 3: numbers parsed eight bytes at a time (85568b4)
The byte-at-a-time parser was about 16% of all samples. Its loop runs once per digit and exits on
the first non-digit, so the exit branch follows the varying number lengths. The new parser reads 8 bytes
as one u64 and finds the separator from bit 4, which every digit has and space and LF don’t. It
then merges up to 7 digits with three multiplies and no branch. Numbers of 8 or more digits take
the old loop; on seed 1 that is 50 of the 5M weights.
- P-cores: elapsed 193 to 216 → 167 to 190 ms, task-clock 2.09 to 2.12 → 1.82 to 1.84 s, cycles 4.66 to 4.71 → 4.03 to 4.05 G, instructions 6.59 → 5.69 G.
- Parse passes: 21 → 9 ms and 31 → 20 ms. The build went from 60 to 37 ms.
- Seed 2: 194 → 168 ms. Seed 3: 201 → 175 ms.
- Peak memory unchanged. S 306 → 317.
Step 4: heap entries as one 128-bit key (542bc46)
Binary-heap operations were 35% of all samples, hash-map probes 23%. Counters on seed 1:
- 7.57M pops, of which 0.45M were stale;
- 20.97M relaxations and 8.65M pushes;
- the heap never held more than 2,719 entries (43 KB).
So the heap’s cost was compares and branches, not memory. Each entry is now distance << 32 | node
in one u128. A (u64, u32) tuple compares the distance, then on a tie the node, which takes
branches. A u128 compares with one subtract-with-borrow and no branch.
- P-cores: elapsed 165 to 169 → 157 to 161 ms, task-clock 1.82 to 1.84 → 1.73 to 1.74 s, cycles 4.04 to 4.06 → 3.80 to 3.81 G, instructions 5.69 → 5.27 G.
- The heap’s share of samples went from 35.0% to 28.2%.
- Seed 2: 171 → 161 ms. Seed 3: 180 → 165 ms.
- Peak memory unchanged. S 317 → 323.
Step 5: 4-byte edges and a fixed mmap threshold (680f4ad)
Where step 4’s peak went, from memory.stat sampled through a seed 1 run: 123.6 of its 127.2 MB
were anonymous memory, and the peak came near the end of the queries. Of that:
- the two CSRs, 2 × (7 MB of offsets + 40 MB of edges) = 94 MB;
- the label maps, about 22 MB: of the 24 searches’ maps, 17 had grown to 57,344 entries (1.1 MB) and 7 to 28,672;
- 5 to 10 MB of free heap space, left behind by label maps that grew;
- the heaps, about 1 MB.
The build’s own buffers were already small (the edge arrays come zeroed from the kernel, and pass 2 parked the places in spare bits), so this step cuts the CSRs and the free space:
- An edge is one
u32: the other end in the low 21 bits at full scale, the weight in the 11 bits above it. A weight that doesn’t fit (3,496 of the 5M on seed 1, among them the heavy edges near 2^32) sets the field to all ones and goes into a small map. The CSRs take 54 MB instead of 94 MB. With no spare bits left, pass 2 writes each edge’s place in its block to au16array, which is freed after pass 3. - Read in place, a 4-byte row is a run of loads by one instruction, 4 bytes apart, and on the i7-13620H that sets off the hardware prefetchers: on seed 1 they brought 113M lines into L2 instead of 55M, and the run took 5% longer. The same records in 8-byte slots did not set them off (55M). So each row of up to 8 edges is first copied to the stack with one 32-byte load.
- Freeing the 10 MB place arrays raised glibc’s mmap threshold to 10 MB. The label maps then came
from the heap, where each map a search outgrew stayed behind as free space. A
mallopt(M_MMAP_THRESHOLD, 64 KiB)at the start fixes the threshold, so an outgrown map is unmapped.
- P-cores: elapsed 158 to 162 → 164 to 167 ms, task-clock 1.75 to 1.78 → 1.80 to 1.82 s, cycles 3.82 to 3.88 → 3.97 to 4.01 G, instructions 5.27 → 5.50 G.
- Peak memory: 126.6 to 129.2 → 81.7 to 81.9 MB.
- Seed 2: 159 → 164 to 166 ms, peak 123.0 to 123.5 → 81.7 to 84.2 MB. Seed 3: 164 → 170 to 171 ms, peak 123.5 to 125.5 → 80.1 to 83.6 MB.
- Knockouts in the same session: without the row copy, 172 to 177 ms, task-clock 1.90 to 1.95 s, peak 81.0 to 82.3 MB; without the fixed threshold, 164 to 165 ms, task-clock 1.78 to 1.79 s, peak 90.6 to 95.6 MB.
- S 323 → 352.
Step 6: the build’s arrays faulted in before pass 2
Round 7 looked at the build. Phase marks on seed 1 (medians of 7 runs on P-cores) split the 157 ms before the output is written into:
- pass 1, 9.5 ms;
- pass 2’s runs, set up on the main thread, 1.2 ms;
- pass 2, 19 ms;
- pass 3, 6.6 ms;
- the heavy edges and freeing the places, under 1 ms;
- the queries, 120 ms.
Outside main, the process takes about 1 ms to start and 2 ms at exit to unmap graph.txt.
Pass 2 parses the same text as pass 1 and writes each edge twice, once per direction, yet took twice
as long. In a run that stopped after the build, 0.21 to 0.24 G of its 0.95 G cycles were in the kernel,
71% of those in clear_page_erms, which zeroes new pages. Pass 2 is the first write to the 60 MB of
edge and place arrays, and every thread writes into every block, so all 12 threads fault on each new
2 MB huge page at once. Each of them zeroes a huge page; the kernel maps one and frees the rest.
Now, before pass 2, half the threads each write one value per 2 MB of their own share of the arrays, so each huge page is faulted in by one thread, bar those that straddle two shares.
- Phase marks (seed 1, 7 runs each, interleaved): pass 2 18.7 → 13.0 ms, plus 3.3 ms for the new step, so 18.7 → 16.2 ms in all, and 156.7 → 154.5 ms before the output. A second session: 19.3 → 16.4 ms, and 158.9 → 155.6 ms.
- P-cores, seed 1: elapsed 164.7 to 165.8 → 161.2 to 167.9 ms (medians 165.3 → 163.7), task-clock 1.80 to 1.82 → 1.74 to 1.76 s.
- Seed 2: medians 170.4 → 166.5 ms, task-clock 1.85 to 1.87 → 1.81 to 1.82 s. Seed 3: 173.6 to 175.8 → 170.1 to 172.1 ms, task-clock 1.90 to 1.91 → 1.84 to 1.85 s.
- With huge pages off (
PR_SET_THP_DISABLE), the new step takes 0.3 ms and pass 2 faults its 4 KB pages as before: 20.8 → 21.2 ms for both, and elapsed medians 173.9 → 173.1 ms. The first version wrote once per 4 KB page. That cost 1.6 ms with huge pages off (20.8 → 22.4 ms), and with them on it did no better (16.5 against 16.2 ms). - This laptop runs Debian 13 with huge pages on for all anonymous memory (
always), and the scoring box runs Debian 13 too. - Peak memory unchanged: seed 1 82.2 to 83.8 → 83.3 to 85.4 MB, seed 2 79.8 to 84.1 → 79.4 to 85.3 MB.
- S 352 → 359.
Step 7: a bucket queue instead of the binary heap
A profile of the queries on step 5 put about 30% of each search step in the heap’s sift-down after a pop (11 dependent levels) and about 25% in label lookups. Prefetching already hid most graph misses: loading edge rows was about 5% of query samples.
Each Search now keeps its frontier in a Queue, a bucket queue in the style of Dial’s
algorithm:
- A key in
cur..cur + 4096, wherecuris the last key popped, goes into bucketkey % 4096of a fixed ring. Keys only grow during a search and every edge weight is non-negative, so a pop takes the lowest non-empty bucket at or aftercur, which a 64-word bitmap finds. - A bucket holds one key, so its LIFO stack stores nodes only:
[node, next]entries linked through one shared arena with a free list, so the arena only grows to the most entries queued at once. A vector per bucket was slower than the heap, from its cache misses. - A key at or past the end of the ring goes to a small binary heap,
far. Weights go up to 2^32-1 (spec §2), and the near-2^32 edges in every seed take this path. The ring’s size is a constant, not something read from the input, so a graph with only huge weights stays correct and pays one heap push per long edge. - The queue knows the next nodes it will pop, so each step prefetches the edge row of the node two pops ahead and the offsets entry of the node three ahead. That replaces the guess at the heap’s children.
- A stale pop (a node already settled at a smaller key) skips the label lookup that used to check
it: its relaxations can never improve a label, so it pushes nothing and leaves
bestalone.
Balancing the two sides by queue length and the stopping rule are unchanged.
Measured on P-cores, interleaved, medians:
| Run | Queries before → after (ms) | Full run before → after (ms) |
|---|---|---|
| Seed 1, quiet machine, 11 runs (on step 5) | 119.75 → 93.11 | 164.69 → 136.48 |
| Seed 1, busy machine, 11 runs (on step 5) | 124.08 → 102.08 | 174.55 → 147.86 |
| Seed 2, busy machine, 7 runs (on step 5) | 129.06 → 106.14 | 175.10 → 151.98 |
| Seed 3, busy machine, 7 runs (on step 5) | 144.63 → 113.68 | 196.23 → 169.70 |
| Seed 1, 11 runs, on step 6 | 160.02 → 133.06 |
Peak memory is unchanged within noise: median 83.2 → 82.8 MB over 9 runs each. S 359 → 450.
Step 8: 24 fewer lines in the query code
Lines count on D more than on any other track (S 450 against a reference of 43), so a pass over
the query code removed what no longer paid for itself. answer uses the on_threads helper
instead of its own scope-and-spawn loop. Search::top only forwarded to Queue::top, so it is
gone. Queue::upcoming returns the next three nodes as an array instead of an iterator.
Queue::clear resets every bucket head with one fill. The rare far heap holds (key, node)
tuples instead of a packed u128. The node hasher hashes in write alone. Every doc comment
stayed.
S 450 → 426. Interleaved full runs, medians (fc4ed14 → step 8): seed 1 133.14 → 133.61, 133.77 → 133.52 and 135.11 → 135.41 ms (11 runs each), seed 2 139.92 → 137.68 ms and seed 3 141.70 → 140.94 ms (9 runs each). Peak memory median 83.7 → 82.9 MB (7 runs each).
Step 9: a 2-byte row index, and pass 3 one direction at a time
Round 8 looked at peak memory, 81 to 84 MB on the board. A time series of the run’s cgroup memory on seed 1 put the peak near the end of the queries, at 82 to 83 MB:
- the two CSRs, 53.9 MB: 2 × 20 MB of edges and 2 × 7 MB of offsets;
- the label maps, 22.3 to 22.8 MB: each of the 24 keeps the size of the largest search it has run, and by the end 17 have 65,536 buckets (1.11 MB) and 7 have 32,768;
- queues, glibc’s arenas, kernel memory and the cgroup’s per-CPU charge stock, about 5 MB.
The build peaked at the end of pass 3, at about 78 MB: 40 MB of edges, 20 MB of places and the 14 MB of offsets that pass 3 writes for the first time. Those writes come from 12 threads at once, and with shares of about 580 KB, 3 or 4 threads fault on each fresh huge page, so the race step 6 describes for pass 2 added spikes of 13 to 25 MB there.
Two changes:
- Pass 3 sorts one direction at a time, so the forward places are freed before the reverse index is written, and it faults each direction’s index in first, one write per 2 MB, as step 6 does for the other arrays.
Csr::offsets, au32per node, becameCsr::rows, au64per group of 4 nodes: the slot of the group’s first edge in the high half, and in each byte of the low half where one node’s edges end, counted from that slot. That is 2 bytes a node instead of 4, 7 MB less at full scale. A group with 255 edges or more keeps its nodes’ rows in a small map instead, and its last byte, 255, sends lookups there. No seed has one (the most edges in a group on seed 1 is 22), but any graph stays correct.sortcounts each node’s degree one slot up, so the counting sort leaves an offsets array for the block, and each group is a window of 5 of it.
Peak memory, memory.peak in MB, 5 runs each, alternating:
| Seed | Step 8 | Pass 3 change alone | Step 9 |
|---|---|---|---|
| 1 | 81.3 to 82.9, median 82.3 | 80.7 to 82.7, median 81.5 | 74.8 to 76.9, median 74.9 |
| 2 | 80.0 to 84.2, median 84.0 | 78.2 to 79.7, median 78.7 | 70.5 to 72.3, median 71.7 |
The peak stays near the end of the queries (74 to 77 MB at 123 to 125 ms in three time series), and the build now tops out at 67 to 68 MB.
Time, on a busy machine (load 17 to 22 from other work on CPUs 12 to 15):
ab.py, alternating full runs, medians, step 8 → step 9: seed 1 151.9 → 151.4 ms (21 runs) and 142.8 → 144.7 ms (41 runs); seed 2 161.1 → 155.7 and 143.1 → 141.8 ms; seed 3 141.9 → 144.2 and 152.1 → 151.0 ms.perf stat -r 5on P-cores, 4 rounds: seed 1 elapsed medians 137.2 → 137.3 ms, cycles 3.26 to 3.28 → 3.31 to 3.33 G, instructions 4.75 → 5.04 G; seed 2 144.3 → 141.6 ms, cycles 3.37 to 3.45 → 3.44 to 3.48 G. Decoding the groups costs 6% more instructions, which the cache misses around them hide.
Correctness: the gate passes, 509 of 509. No seed has a wide group, so 200 generated graphs check them against step 8: 60 random graphs with hub nodes, and 140 with one group of 4 hubs whose every edge leads to or from a node of its own, so each answer says which hub owns the edge. They cover groups of 254 and 255 edges, empty nodes, the first and last group of a block, and a last group cut short by n. All 200 outputs are byte-identical to step 8’s, and with the wide rows emptied, 54 of the 60 random graphs changed.
S 426 → 443.
Step 10: label distances aligned to 4 bytes
After step 9 the label tables were the biggest item at the peak after the graph. Each of the 24
keeps the size of the largest search its thread ran, about 23 MB in all at full scale. A
HashMap<u32, u64> entry is 16 bytes, 4 of them padding after the key. Labels now maps to
Dist, a u64 in a #[repr(C, packed(4))] struct, so an entry is 12 bytes, and a slot with its
control byte 13 instead of 17.
- Peak memory, 5 runs each, alternating: seed 1 74.4 to 76.6 → 69.6 to 71.7 MB (medians 75.8 → 71.3), seed 2 70.5 to 73.1 → 67.6 to 68.8 MB (medians 71.5 → 67.8).
ab.py, alternating full runs, medians, step 9 → step 10 (31 runs each): seed 1 136.1 → 134.7 and 136.7 → 136.8 ms, seed 2 137.9 → 135.8 and 137.3 → 136.1 ms, seed 3 142.7 → 141.4 ms.perf stat -r 5on P-cores, seed 1, 3 rounds: task-clock 1.430 to 1.451 → 1.416 to 1.431 s, cycles 3.25 to 3.30 → 3.22 to 3.27 G, instructions 5.04 → 5.11 G.- S 443 → 445.
Step 11: the queue tops kept between steps
Steps 10 and 11 went to the board in one push, so both rows cite run-37fab0938045.
A time split of step 7 on seed 1: the build takes 35 to 43 ms, the queries 93 to 105 ms, the output
0.08 ms. The search loop asked both queues for their top on every iteration, but a step moves
only its own side’s top. step now returns its queue’s new top, and distance keeps the other
side’s. The side that did not step has an unchanged queue, so its top and the bucket cursor that
pop relies on are still valid, and the stop rule sees the same values as before.
ab.py against step 9, alternating full runs on seed 1, five sessions on a busy machine (load
9 to 12), medians: 158.5 → 155.4, 142.9 → 139.7, 139.6 → 137.9, 138.8 → 134.3 and 142.2 → 139.8 ms,
faster on median and minimum in all five, about -2.1% on average. The query phase alone, two
sessions of 21 runs: 96.8 → 94.3 and 97.9 → 94.6 ms. S 445 → 447. Gate: 509 pass, 0 fail.
Measured and not taken: the last threads idle for 3 to 5 ms at the end, because the top 5% of queries use 53% of the CPU and their cost can’t be predicted, so no cheap reordering helps. Label and queue resets cost about 0.5 ms of wall time, and the 20 duplicate queries of a seed about 0.7 ms, which would take about 10 lines to remove.
Step 12: pass 2’s runs as two iterators
A phase split of step 11’s build on seed 1, medians of 25 runs: pass 1 9.5 ms, faulting the arrays in 3.3, the runs set-up 1.4, pass 2 12.9, the heavy edges 0.4, pass 3 3.3 and 3.5. The queries took 91.3 ms. Pass 1 is bound by instruction throughput, about 91 instructions per line. Pass 2 parses the same text again and makes 4 scattered stores per line; a faster parse did not shorten it (see the AVX2 row below).
Pass 2 appends every edge to one run in each direction, picked by its block, so a thread reads
and writes its 2 × 850 runs at random. A run was a zip of the edge-slot and place-slot
iterators, which keeps an index and two lengths besides the two iterators: 48 bytes. The two
iterators alone take 32, so a thread’s runs take 54 KB instead of 82 KB, and append advances
each iterator itself.
Phase marks, 25 rounds each on seeds 1 and 2, medians: runs set-up 1.36 → 1.14 and
1.35 → 1.13 ms, pass 2 12.90 → 12.63 and 12.93 → 12.43 ms. ab.py against step 11, 41
alternating runs per binary and session, medians: seed 1 133.04 → 131.35, 132.56 → 130.69 and
133.92 → 131.67 ms, seed 2 133.50 → 131.97, 133.83 → 132.26 and 139.53 → 137.15 ms, seed 3
139.91 → 137.89 ms. About 1.2 ms of that is code placement. With every function aligned to 64
bytes in both builds (-C llvm-args=-align-all-functions=6, for this control only), the gain was
0.2, 0.6, 0.8 and 1.3 ms in four sessions, which matches the phase marks.
Peak memory, medians: seed 1 70.3 → 70.35 MB (10 runs each), seed 3 69.6 → 69.5 and seed 4 67.7 → 67.9 (5 runs each). Seed 2 rose from 67.6 to 68.25 MB over 10 runs. Its build maximum stayed at 67.4 to 68.0 MB, but its query phase ended about 1 MB higher in anonymous memory in three traced runs. The query code is unchanged, so this is most likely where the heap’s pieces landed. S 447 → 448. Gate: 509 pass, 0 fail.
Step 13: labels as u32 distances
After step 12 the peak still came near the end of the queries, and the 24 label tables made about
17.5 MB of it: 13 bytes a bucket, 17 tables at 65,536 buckets and 7 at 32,768. A label is now a
u32 in the first of two maps, so a bucket takes 9 bytes. A label of 2^32-1 or more, which only
a path over one of the edges near 2^32 can have, is u32::MAX in the first map and its full value
in the second.
A new label starts at u32::MAX, so a via below 2^32-1 beats it with the one compare a
relaxation already made, and a miss in the first map is final. The second map is read only when
via itself reaches 2^32-1, and for the other side’s label only behind a u32::MAX. On seed 1
the other side has the node in 5,031 of the 8.65M lookups.
- Peak memory, 6 alternating runs each, seed 1: 69.86 to 71.17 → 67.34 to 68.29 MB, medians 70.30 →
67.70. In a trace of
memory.currentthe queries now end at about 64 MB, and the peak moved to pass 3 of the forward direction, while the edges, both place arrays and the forward rows are alive. So 2.6 of the 5 MB show. ab.py, alternating runs, medians (minimums). 41 runs per binary on a quiet machine: seed 1 131.91 → 129.91 (129.43 → 127.95) ms, seed 2 135.69 → 132.73 (131.67 → 130.21) ms. 31 runs per binary on a machine busy with other work: seed 1 143.00 → 140.84 (137.64 → 134.68) and 149.72 → 150.48 (142.40 → 139.80) ms, seed 2 144.80 → 142.43 (138.61 → 136.59) ms, seed 3 153.32 → 151.24 (140.77 → 140.55) ms.perf stat -r 5on P-cores, seed 1: task-clock 1.547 → 1.528 s, cycles 3.69 → 3.65 G, instructions 5.15 → 5.20 G. The smaller tables miss the caches less: at 65,536 buckets, the four tables of a core’s two threads take 2.4 MB instead of 3.4 MB.- S 448 → 453. Gate: 509 pass, 0 fail. Fresh seeds 5 to 9, 31 and 47: byte-identical to the reference.
Step 14: 11 fewer lines
The six single-item use lines become one; M_MMAP_THRESHOLD, PROT_READ and MAP_PRIVATE
are written as numbers at their one call each, with their names and meaning in the comment above
it; map_file passes file.as_raw_fd() straight to mmap; and main and build_graph each
declare a pair of variables together. .text and .rodata are byte-identical to step 13’s, so T
and M cannot move. S 453 → 442. Gate: 509 pass, 0 fail.
Steps 13 and 14 went to the board in one push, so both rows cite the same run.
Step 15: 1 fewer line
sort declares its counters and its running sum together. .text and .rodata are
byte-identical to step 14’s. S 442 → 441. Gate: 509 pass, 0 fail.
Step 16: the queue’s push inline
LLVM kept Queue::push out of line, so every relaxation in Search::step paid for a call and
its spills. #[inline(always)] puts it in the loop (pedantic clippy’s inline_always is allowed
in Cargo.toml, with the reason). Local, AC power, turbo off, seed 1, 12 threads: perf stat,
5 runs, twice: instructions 5.188 → 5.093 G and 5.206 → 5.112 G (-1.8%), cycles 3.485 → 3.310 G
and 3.555 → 3.442 G, task-clock 1,458 → 1,384 ms and 1,487 → 1,440 ms. ab.py, interleaved
against step 15, medians (minimums): 31 runs, 132.43 → 130.56 ms (130.38 → 126.92); 41 runs,
135.63 → 130.98 (128.91 → 126.39); 41 runs, 133.52 → 130.68 (128.87 → 126.43); and on a first
build, 31 runs twice, 131.09 → 127.92 and 132.38 → 128.69. memory.peak cannot move, as push
runs only in the queries, and did not: 6 alternating runs, median 67.90 → 67.89 MB, highest
68.17 → 68.22. S 441 → 442. Gate: 512 pass, 0 fail (full seeds 1 to 12 and every tiny
seed).
After step 16: where memory.peak comes from, and label changes that did not pay
Four query-side changes and one build-side change, each measured against step 16 (or step 15 where noted). None paid, so the code is step 16’s. Rows in the table below.
Where memory.peak comes from, read from the cgroup at phase marks (seed 1, 12 threads, 3
runs, peak 66,044 to 66,516 KiB): it is reached at the end of pass 3’s first direction. Then both
edge arrays (38.15 MiB), both place arrays (19.07 MiB) and the forward rows (3.32 MiB, written as
4 KB pages by all 12 threads) are live at once, with about 4.4 MiB on top: the process and its
wrapper, page tables (520 KiB), slab, and the memory cgroup’s per-CPU charge batches. The
queries top out lower, at about 62,100 KiB (an earlier memory.current trace), with 12 threads’
label tables grown to 32,768 or 65,536 buckets. So a cut to the labels alone cannot move M until
the build peak falls by about 4.4 MiB. It also explains the measured peaks below: u16 labels
save 2 to 3 MB in the queries and nothing in the peak.
Step 17: pass 3 gives back the places it has sorted
A phase trace of step 16 (seed 1, memory.current and memory.peak of the cgroup at each phase
mark, KiB, 3 runs) put the peak at the end of pass 3’s first direction, 65,856 to 66,048, against
62,356 to 62,388 at the end of pass 2 and 60,488 to 62,632 when the query threads finish. The difference
is the forward rows, written while both directions’ places are still alive, plus the sort’s
buffers.
Pass 3 now deals the blocks out in turn: thread i sorts blocks i, i + 12, i + 24 and so on, in
order, and after each block stores where that block’s places end. Below the least of the 12
stored ends every place belongs to a sorted block (a block that reaches below it is behind its
own thread’s last one), so after each block the whole 2 MB pages below it that are not yet
dropped go back with madvise(MADV_DONTNEED). The bounds are 2 MB aligned because a dropped part
of a huge page stays charged until the rest of it goes. The reverse direction runs the same code.
- Phase trace after (seed 1, 5 runs, KiB): pass 2 ends at 62,192 to 62,872, the forward pass 3 tops out at 63,436 to 64,448, and the query threads end at 62,948 to 63,652. The forward pass still adds about 1.2 MiB: the first huge page of places goes only once the slowest thread is past it, and the 4 KB pages before it stay.
- memory.peak, MiB, 6 alternating runs each: seed 1 63.9 to 64.4 → 61.9 to 62.7 (medians 64.1 → 62.25) and 64.0 to 64.6 → 61.8 to 62.4 (64.3 → 62.15); seed 2 63.9 to 64.5 → 61.8 to 62.7 (64.1 → 62.35); seed 3 64.0 to 64.7 → 61.8 to 62.7 (64.2 → 62.15).
ab.py, 41 alternating runs per binary, medians (minimums): seed 1 128.75 → 128.01 (126.90 → 126.43) ms; seed 3 134.67 → 135.20 (132.45 → 132.43) ms. Before two line cuts that leave the logic as is (anifaround the call, and acquire/release orderings): seed 1 128.57 → 128.08 and 128.84 → 129.01, seed 2 129.70 → 130.59 ms. A tie.- S 442 → 449. Gate: 512 pass, 0 fail.
The three levels are now within about 1.5 MB of each other: the end of pass 2 (both edge arrays and both place arrays, 57.2 MiB, with about 4.5 MiB of process, page tables and the cgroup’s per-CPU charge batches), the forward pass 3, and the queries. A lower M needs all three to fall, and the places only shrink with a slower build (the transposed build below took 6.5 ms).
Step 18: 30 fewer lines
S counts code lines after rustfmt, and the Dockerfile’s lines too. rustfmt’s defaults break a chain, a call’s arguments or a tuple past 60 characters, so most cuts below are forms that stay under those widths rather than longer lines. Net code lines per change:
- The Dockerfile’s build stage runs
cd /src && cargo buildwith the context mounted, as track A does, instead of settingWORKDIRand copying it: 7 → 5. Built withdocker build --network=none, the binary is byte-identical to the local cargo build (ef900b06). for_each_line::<N>parses a line of N numbers into an array, so the edge lines and the query lines share it: -4. The queries are kept asu32pairs, soanswerstoresdistancewith no binding: -1.split_runscuts withsplit_off_mut: -4.sort’s prefix sum is afold: -2.map_filemaps at least one byte, so an empty file (an empty queries.txt) needs no branch: the mapping of an empty file succeeds and the empty slice never reads it. -3.line_chunkscomputes each split point in a closure, fromat - 1on: -2. Its chunks differ from step 17’s by at most a line at each split, which only reorders edges inside a row.prefetchtakes anOptionandCsr::prefetchis gone, sostepmakes its two prefetches in two lines: -6.- Smaller ones, -1 each: the two arguments through one closure (track A’s form),
startreturns the queue’s top asstepdoes,unpackmapped over the row,unpackand the row copy declared together,Queue::newwithout itsDefault::default()binding, andahead’s word and bit read fromfromdirectly.
step, with push and pop inlined, has the same machine code as step 17’s, and pass 1 too but
for one equivalent compare (cmp 9; ja for cmp 10; jae) in its slow digit loop. Pass 2 has one
more instruction per line: LLVM now lays the heavy-weight test out as a not-taken branch and a jump
instead of a taken branch. Pass 3’s prefix sum and the per-query code changed.
Code placement mattered. A first version had step’s start 32 bytes past a 64-byte line instead
of 16, with the same machine code, and that cost 0.4 to 0.5% of cycles (perf stat, 8 and 10
interleaved rounds, never lower than step 17; perf record put all of it in step). With every
function aligned to 64 bytes (-C llvm-args=-align-all-functions=6, for this control only), step
17’s code and this step’s both lost 0.4 to 0.5% too. Reading the arguments through one closure moves
step back to 16, and that is the version kept.
Local, turbo off, against step 17, seed 1 unless named:
perf stat, 10 interleaved rounds of 5 runs: instructions:u 4,991.5 → 4,996.2 M (+0.09%, pass 2’s extra instruction), cycles:u median 3,056.4 → 3,059.3 M (+0.1%, lower in 3 of the 10 rounds).ab.py, 41 interleaved runs, medians (minimums): seed 1 127.17 → 127.45 (125.01 → 126.47), 127.40 → 127.64 (125.52 → 125.41) and 127.69 → 127.42 ms (124.65 → 126.06); seed 3 133.02 → 133.32 (131.07 → 131.46), 132.59 → 132.72 (131.06 → 130.80) and 133.26 → 133.10 ms (131.56 → 131.01). In the third round a second copy of step 17’s binary ran too: 127.60 and 133.46 ms. About +0.07% on average, within the spread of the two copies.- memory.peak, alternating runs: seed 1 median 62.4 → 62.1 MB (5 runs each), seed 3 62.2 → 62.35 MB (10 runs each, 61.8 to 63.0 against 61.8 to 63.7).
- S 449 → 419 (Rust 442 → 414, Dockerfile 7 → 5). Gate: 512 pass, 0 fail;
cargo fmt --checkand clippy report nothing. An empty queries.txt, a graph with no edges, and files without a final LF give the same output as step 17.
Step 19: graph.txt’s pages dropped by the threads that finish first
A phase timeline of step 18 (seed 1, P-cores, medians of 11 to 21 runs, ms from the spawn):
main starts at 1.9-2.2; pass 1 ends at 11.5-11.8 (its last thread starts 0.9 ms after the
first); the faulting takes 3.4-3.6, the runs set-up 1.2 (380 page faults), pass 2 12.5, pass 3
3.4 and 3.7; the queries run from 36.7 to 124-125, and the first query thread is done 5 ms
before the last, so the threads idle for 39-42 ms of CPU time at the end (3.5 ms each on
average). Then the output takes 0.15 ms and the exit 2.1-3.9 ms. Kernel time is 4.6% of all
cycles (148 M of 3.21 G).
Most of that exit is graph.txt: a munmap of it before the exit took 2.45 ms (1.3 ms after a
reboot, likely from the page cache’s pages lying closer together), and the exit then took 1.3
ms. Step 12’s not-kept rows dropped those pages from busy threads, in pass 2 or from a 13th
thread during the queries, which moved the cost instead of hiding it. Now each query thread,
once the counter has no query left, drops every threads-th 8 MB piece of the mapping
(madvise(MADV_DONTNEED)), on a CPU that would otherwise wait for the last query. The last
thread to finish still drops its own twelfth, about 0.1-0.2 ms.
step‘s machine code is unchanged and starts 16 bytes past a line, as in step 18 (the queries’
Search pair is built by an array map, which put it there).
ab.py, 41 interleaved runs, medians (minimums): seed 1 126.72 → 125.33 (124.49 → 123.37), 126.97 → 125.18 (124.32 → 123.50); seed 3 133.03 → 131.74 (130.69 → 129.76), 132.16 → 131.25 (130.82 → 129.45); seed 2, on a busy machine, 131.81 → 131.57 (126.01 → 125.54) ms. About -1.0% on seeds 1 and 3.- Before a reboot of the machine, a first version (2 MB pieces taken from the query counter, with
step32 bytes past a line), seed 1: 127.13 → 125.15 ms (125.26 → 123.82). - memory.peak, 5 alternating runs, seed 1: 61.8-63.7 → 62.1-62.5 MB (medians 62.1 → 62.2).
- S 419 → 422. Gate: 512 pass, 0 fail;
cargo fmt --checkand clippy report nothing. An empty queries.txt and a graph with no edges give the same output as step 18.
Step 20: the build’s serial parts
Step 19’s timeline has two serial steps on the main thread between the parallel passes: pass 2’s runs set-up, 1.1-1.2 ms with 380 page faults, and the heavy edges’ two maps, 0.3 ms.
split_runsreturned aVecof its runs. Pass 2’s set-up collects four of them, 10,200 slices of 16 bytes each, and at 163 KB each is a freshmmapunder step 5’s threshold, so each costs 40 page faults and an unmap. It now returns an iterator over the runs, cut as they are asked for: 380 → 207 faults, and the set-up 1.13 → 0.63 ms (phase marks, 21 runs).Csr::heavyhashed its (node, other end) keys with std’sSipHash. It now usesNodeHash, whosewritexors each id into its state before the multiply, so a label’s one id hashes as before (state 0) and a pair mixes both: the heavy step 0.32 → 0.15 ms.step’s instructions are the same as step 18’s; one field offset moved, asheavy’s hasher is now zero-sized.- The build ends 0.64 ms earlier (35.67 → 35.03 ms, medians of 21 runs).
stepstarts 16 bytes past a line (the two graphs passed as an array again, and theSearchpair as a tuple).
ab.py, 41 interleaved runs, medians (minimums), step 19 → step 20: seed 1 124.63 → 123.92
(122.48 → 122.05) and 125.98 → 124.76 (123.33 → 122.44); seed 3 132.49 → 131.07 (129.41 →
128.89) and 132.71 → 131.83 (129.92 → 129.22); seed 2 127.40 → 126.22 (125.15 → 124.02) ms. About
-0.85%, and about -1.5% against step 18 in the same rounds. memory.peak, alternating runs: seed 1
61.8-64.5 → 61.8-62.7 MB (medians 62.35 → 62.25, 10 runs each), seed 3 61.9-62.7 → 62.0-64.3 MB
(medians 62.55 → 62.7, 6 runs each); both builds show the rare 64 MB runs. S 422 → 424. Gate:
512 pass, 0 fail; cargo fmt --check and clippy report nothing.
After step 20: the graph’s structure, measured for two pruning ideas (not built)
The queries take about 89 of step 20’s 124 ms (the build ends at 35 ms), so a large gain has to come from settling fewer nodes. Two ideas need no preprocessing beyond the build, so we measured how much each could save on seed 1 (a Python script over graph.txt, counting each node’s distinct neighbours with edge direction ignored):
- Neighbours per node: 17 nodes have none, 101,147 have one, 441,141 two, 701,013 three, 444,748 four and 52,446 five or more.
- Dead-end trees. Peeling one-neighbour nodes until none is left leaves a core of 1,622,683 nodes. The other 117,829 (6.8%), the 17 isolated ones aside, sit in trees that each hang off a single core node, and a search never needs to enter a tree that holds neither s nor t. So pruning them saves at most 6.8% of the settled nodes, and costs a bit test on every relaxation.
- Chains. 476,632 of the core’s nodes (29%) have exactly two neighbours. Contracting those chains into shortcut edges would settle up to that many fewer nodes. It costs a contraction pass in the build, a third edge array, and special cases for an s or t inside a chain.
Both at their ideal settle about 34% fewer nodes, so at most about 30 ms of the 89. We did not build either: the time left before the freeze would not cover both the build and a check of every edge case against the hash, and track D is not one of our three scored tracks.
Tried and reverted (local, turbo off, no run ID)
Each row’s baseline ran in the same interleaved session as the experiment, so baselines differ between rows.
| Experiment | Local result (P-cores, seed 1) | Why it lost |
|---|---|---|
Prefetch offsets[next] at every push, alone | 281 to 285 ms, task-clock 3.16 to 3.18 s, against 289 to 291 ms and 3.26 s | It also fetches nodes that are settled much later, or never |
| The push prefetch together with step 2b’s prefetch | 208 to 210 ms, task-clock 2.34 to 2.35 s, against 202 to 207 ms and 2.26 to 2.27 s for step 2b alone | The extra prefetches cost more than they hid |
| That pair, plus the last line of the next node’s edge row | 209 to 210 ms, task-clock 2.33 s, against 208 to 210 ms and 2.34 to 2.35 s without it | No gain in elapsed time |
| Step 2b’s prefetch placed before the stale-entry check | task-clock 2.27 to 2.28 s against 2.26 s; elapsed 202 to 205 ms against 203 to 208 ms, leaving out one noisy round | A tie, and 3 more lines after rustfmt |
| Prefetch only the closer of the root’s two children | 192 / 224 / 194 ms, task-clock 2.10 to 2.12 s, against 189 / 217 / 191 ms and 2.08 to 2.11 s for both | Slower than prefetching both |
| Also prefetch the root’s four grandchildren | 191 to 195 ms, task-clock 2.13 to 2.14 s, against 190 to 194 ms and 2.12 s | No gain |
Transparent huge pages off (prctl(PR_SET_THP_DISABLE)) | 227 to 240 ms, task-clock 2.48 s, cycles 5.68 G, peak 125.5 to 129.2 MB, against 211 to 230 ms, 2.35 s, 5.24 G, 124.6 to 127.3 MB | The CSR was already 86 of its 94 MB on huge pages mid-run. Its arrays are fully used, so there is no padding to save, and its random reads miss the TLB more on 4 KB pages |
MADV_HUGEPAGE on the CSR | Not built | Only the unaligned array ends (about 8 MB) are on 4 KB pages. Scaled from the 5.5% that all-4 KB pages cost, that is at most about 0.5% |
| 4-ary heap, child picked by a loop | 202 to 205 ms, task-clock 2.24 s, 6.71 G instructions, against 166 to 168 ms, 1.83 to 1.84 s, 5.69 G | 18% more instructions. The heap tops out at 43 KB and stays in cache, so fewer levels save no misses |
| 4-ary heap, child picked without branches | 212 to 213 ms, task-clock 1.96 to 1.98 s, against 201 to 205 ms and 1.86 to 1.88 s (two rounds, on a busy machine) | The same: std’s binary heap is already cheap per level on a heap this small |
| Radix heap, with each bucket’s minimum kept on push | 203 to 208 ms, task-clock 2.25 to 2.31 s, cycles 4.92 to 5.07 G, against 170 to 171 ms, 1.85 to 1.87 s, 4.04 to 4.05 G | It can’t name the node after next, so step 2c’s prefetch is lost, and bucket bookkeeping costs more than a 43 KB binary heap |
Labels as u32 distances, with the rare longer ones in a second map (on step 4) | 163 to 170 ms, task-clock 1.81 s, 5.65 G instructions, peak 114 to 116 MB, against 156 to 158 ms, 1.73 s, 5.27 G, 125 to 128 MB | 7% more instructions and 28 more lines to save 11 MB |
| Step 5’s rows read in place, but with an NTA hint on the row prefetch, in reverse order, or even edges then odd ones from one load instruction | cycles 4.14 to 4.35 G, 98 to 129M L2 prefetches, against 4.07 G and 113M read in place (counters, one perf stat -r 3 each) | The extra prefetches stayed |
| Step 5’s rows read as 8-byte pairs, or even and odd edges from two load instructions | 55 to 60M L2 prefetches, but 5.85 to 5.93 G instructions and cycles 4.07 to 4.12 G, against 5.45 G and 4.07 G read in place (same session) | The extra instructions ate the gain |
Step 5’s row copied by a memcpy of its exact length | cycles 3.97 G, 5.71 G instructions, against 3.91 G and 5.50 G for the 32-byte copy (same session) | A library call per row |
| A 16-byte copy for rows of up to 4 edges | 89M L2 prefetches, cycles 3.99 G, against 55M and 3.91 G for the 32-byte copy (same session) | Rows of 5 to 8 edges still set the prefetchers off |
| Two or four lines parsed at once per thread, interleaved, in both parse passes (on step 5, phase marks) | Two: pass 1 9.5 → 8.5 ms, pass 2 19.0 → 21.5 ms, 157.1 → 158.1 ms before the output. Four: 10.4, 22.6 and 162.6 ms | Pass 2 lost more than pass 1 gained |
| Blocks of 4,096, 8,192, 16,384 or 32,768 nodes instead of 2,048 (on step 5, phase marks) | Runs set-up 1.2 → 0.6 / 0.3 / under 0.2 / under 0.2 ms, pass 2 19.1 → 18.6 / 18.2 / 17.8 / 17.6 ms, but pass 3 6.6 → 7.6 / 14.5 / 12.6 / 15.4 ms, so 157.0 → 156.6 / 162.5 / 161.5 / 165.8 ms before the output | A tie at 4,096, and pass 3 slower beyond. Past 64 KB a block’s copy is a fresh mmap; with one buffer per thread reused instead, pass 3 took 6.6 / 7.7 / 8.8 / 9.9 ms at 2,048 / 4,096 / 8,192 / 16,384, against 6.8 ms for the copy at 2,048 |
| Step 6’s faulting on all 12 threads, or on a third of them | Faulting plus pass 2: 17.1 and 17.2 ms, against 16.4 ms on half (one write per 2 MB). With one write per 4 KB, 17.7 against 17.0 ms | Zeroing is memory traffic, and more threads only contend for it |
| Step 6’s faulting for the edge arrays only | 2.8 + 15.9 = 18.6 ms, against 4.3 + 12.4 = 16.7 ms for all four arrays and 18.8 ms for none (one write per 4 KB) | Pass 2’s first writes to the place arrays race the same way |
| Faulting inside pass 1, with the arrays sized from the header’s edge count | Pass 1 9.5 → 15.2 to 15.9 ms, and 158.6 to 159.0 ms before the output, against 157.6 ms with step 6’s separate step and 160.6 ms with neither | The parse slowed by more than the separate step takes |
| Faulting during pass 1 on 6 extra threads, or on the main thread | Pass 1 9.6 → 23.4 ms (fastest 13.5) and 17.6 ms (fastest 13.8) | The 12 parse threads already fill the 12 CPUs |
| Unmapping graph.txt and freeing the place arrays on background threads | 160.5 ms median with both, 160.4 ms without the unmap, 161.8 ms without the background free (5 rounds) | No gain in elapsed time worth the lines |
A cheaper bounds check in number | Pass 1 fastest 9.39 ms, against 9.43 ms | No gain |
| Pass 2’s run lists sized up front | Runs set-up 1.28 → 1.10 ms | 0.18 ms is less than the lines cost |
A statically linked binary (-C target-feature=+crt-static) | Start-up 1.0 → 0.73 to 0.77 ms | Not adopted: untested in the Docker build, for about 0.25 ms |
| Relabeling nodes in BFS order, computed during the run (on step 7) | Queries 93.8 → 84.8 ms, but the order took 80 ms and permuting the graph 52 ms. An ideal order from the generator’s coordinates, which a submission cannot use, reached 83.3 ms | Even a 10× faster order would only about break even |
| A locality-preserving hash for the label table, on the ideal order above (on step 7) | Queries 110.9 ms against 83.3 ms with the multiplicative hash on the same order | Slower |
| Labels as 32-bit distances with a fallback map (on step 7) | Queries 95.2 against 93.1 ms, 0.9 MB saved | Slower, for little memory |
| A ring of 1,024 or 2,048 buckets instead of 4,096 | Queries 94.9 and 96.2 against 93.1 ms. Re-measured after the line-count pass: 95.9 against 93.5 ms, and 96.2 with Queue deriving Default, which a 2,048 ring allows (10 lines fewer) | Not from the far heap: at 2,048 only weights 2,047 to 4,095 move there, 0.07% of edges. Cause not found |
| Balancing the two sides by label count, which drops the queue’s length counter (3 lines fewer) | Queries 96.6 against 95.0 ms | Slower |
Linear-probing and epoch-packed label tables instead of HashMap | Lost clearly to hashbrown | Its control bytes make failed lookups cheap |
Exact pruning on via + other_top >= best, or checking the other side when a node is settled | Correct, no speedup | |
| Prefetching the 4th or 5th node ahead, or pre-warming the label slots of the next node’s neighbours | No gain | |
| Balancing the two sides by pop count instead of queue length | Slower | |
| Label maps emptied after each query once they pass 14,336 entries, or 28,672 (on step 7, with step 9’s pass 3 change) | Peak 72.0 to 72.7 MB against 80.9 to 82.6, but elapsed median 148.6 against 134.7 ms, task-clock 1.55 to 1.57 against 1.41 to 1.42 s | 10% slower: the next big search regrows its map from empty, rehashing at every doubling into freshly mapped pages |
| Step 9’s pass 3 change without faulting the offsets in first (on step 7) | Peak 80.9 to 85.2 MB against 80.6 to 83.7, elapsed median 137.2 against 134.1 ms | More threads first-touched each fresh huge page |
| Pass 1 parsed with AVX2: one 32-byte compare finds a line’s three separators (on step 11, phase marks) | Pass 1 fastest 9.4 to 9.5 → 7.6 to 7.8 ms, pass 2 unchanged, S +24 | 1.3% of T for 5% more lines, a small loss on the score |
| A write prefetch of a run’s next slots in pass 2, three placements (on step 11, phase marks) | Pass 2 fastest 15.1 to 15.2 ms against 12.8 ms | Slower |
sort’s counters in a stack array of BLOCK + 1 instead of a Vec per block (on step 11) | Medians 133.30 and 133.63 ms against 133.31 and 133.57 ms (seeds 1 and 2) | No change |
Each pass 2 thread drops its chunk’s pages of graph.txt from the page tables (madvise(MADV_DONTNEED)) when it is done, so that the exit has none to unmap (on step 12) | Medians 131.11, 132.27, 131.01 and 131.92 ms against 131.35, 131.97, 130.69 and 132.26 ms (seeds 1, 2, 1, 2) | A tie, for 4 lines. Unmapping them at the exit takes about 1.7 ms on one thread, and the calls cost about as much, likely in the TLB flushes they send to the other threads |
The same madvise on all of graph.txt from a 13th thread during the queries (on step 12) | Medians 132.09, 155.11, 133.53 and 133.61 ms against 131.67, 154.59, 132.94 and 132.81 ms | 0.4 to 0.8 ms slower, likely from the CPU time it takes from the 12 query threads and the TLB flushes it sends them |
A static-pie build (+crt-static, as tracks A and C use), on step 12 | ab.py, 30 interleaved runs, median / min 132.21 / 130.34 ms against 132.01 / 130.38 ms; memory.peak, 6 alternating runs, 70.1 to 72.1 against 70.1 to 71.7 MB | No gain: the dynamic loader’s quarter of a millisecond is 0.2% of the run |
Each pass-2 thread drops its chunk’s pages of graph.txt (madvise(MADV_DONTNEED), 3 lines), so the exit has fewer to unmap, as track B’s step 17 does | ab.py, 30 interleaved runs, medians 132.68 → 131.95, 133.93 → 134.01 (seed 2) and 133.41 → 133.53 ms, minimums 0.6 to 1.3 ms lower; kernel cycles 155 to 157 → 163 to 165 M | No gain in the median: 22k page-cache entries take little time to unmap, and the drops interrupt the threads still parsing |
| A node’s edge back to the node that labelled it skipped, with that parent carried in the queue entry, and a label’s old ring entry unlinked when the label improves (on step 12) | ab.py, 31 runs: the skip alone 132.85 → 133.60 ms, both 132.25 → 132.40 ms (medians). Instructions 5.10 → 4.98 G, branch misses 19.0 → 23.6 M, cycles 3.36 G in both | The skip is a branch on the data that mispredicts, and the 450k stale pops of 7.57M (seed 1) that the unlinking removes saved no time |
| Every label table made with room for 32,768 labels (65,536 buckets) from the start, to skip its growth (on a first version of step 13) | ab.py, 31 runs, same session: median 130.67 → 135.73 ms | Most queries had run in 32,768 buckets; spread over twice as many, their labels miss the caches more |
Line cuts that change the machine code, on step 12: split_runs through split_off_mut (4 lines), sort’s prefix sum as a fold (3), its copy iterated in the loop header (1) | .text differs from step 12’s in 4,175 and 573 lines of disassembly with addresses stripped; the third keeps it but draws a clippy warning (unnecessary_to_owned) | Not measured: code placement alone moved this track’s time by about 1 ms (step 12) |
| A search’s first 3,584 labels kept in a table of their own, 4,096 buckets that stay in cache, and only its later labels in the grown table (on step 14; also 1,792 and 7,168) | ab.py, 31 runs, same session: medians 171.56, 178.75 and 159.66 ms against 130.22 ms. Branch misses 18.9 → 43.6 M, cycles 3.32 → 4.42 G (3,584) | Once the small table is full, every lookup asks it first, and its answer is a branch on a load that mispredicts |
| The side with the smaller queue top advanced instead of the side with the shorter queue, while both tops are below 2^32 (on step 14) | ab.py, 21 runs: median 133.19 → 138.99 ms, min 129.42 → 134.71 ms | Equal radii settle more nodes than equal frontiers on this graph |
| The node hash without its multiply: the id as it is, and its low 7 bits copied to the top for hashbrown’s tag (on step 14) | ab.py, 31 runs: median 130.96 → 146.39 ms | The tag then repeats the slot’s own low bits, so any label whose home is the same slot matches it, and a miss loads a bucket far more often |
| The edge back to the parent left out with no branch: the parent rides in the queue entry, and a compare over the 8 copied edges moves its edge last and drops it (on step 15) | ab.py, 31 runs: median 131.53 → 135.38 ms. Branch misses 18.9 → 17.0 M, but instructions 5.15 → 5.20 G and cycles 3.36 → 3.44 G | The parent’s label is a cache hit, so its relaxation was cheap; the compare and the wider queue entries cost more |
Labels as u16 distances, keys packed to 2-byte alignment so a bucket takes 6 bytes, longer labels behind a u16::MAX in the second map (on step 16) | ab.py, 31 runs, two rounds: medians 128.02 → 127.34 and 128.47 → 129.36 ms, minimums 126.56 → 125.93 and 125.85 → 126.20. perf stat on step 15: cycles -1.2%, instructions +0.6%, L1 misses +1.8%. memory.peak, 6 runs: median 67.89 → 67.62 MB, highest 68.17 → 68.10 | A tie in time, and the label memory it saves sits below the build peak |
One label table per thread for both sides, [u32; 2] per node, so the relaxation reads the other side’s label from the same bucket instead of a second lookup (on step 16) | ab.py, 31 runs, three rounds: medians 127.38 → 131.05, 128.02 → 130.70, 128.47 → 131.54 ms. perf stat: instructions 4.994 → 4.977 G, but cycles 3.063 → 3.156 G and L2 load misses 3.55 → 4.65 M | The joint table holds both searches’ nodes in 12-byte buckets, 128 Ki of them for the big queries, and that misses L2 more often than the saved lookup gained |
The same joint table with [u16; 2], 8-byte buckets (on step 16) | ab.py, 31 runs, two rounds: medians 128.02 → 128.64 and 128.47 → 130.07 ms. memory.peak, 6 runs: median 67.89 → 67.75 MB, highest 68.17 → 67.81 | Still slower; the memory sits below the build peak |
Labels in a dense u32 array per search, 2^21 slots, reset through a list of touched nodes (on step 15) | ab.py, 11 runs: median 131.04 → 243.08 ms | 24 arrays of 8 MiB written in full on first use, about 200 MB of page faults and zeroing |
#[inline(always)] on Search::step (on step 15) | perf stat, 5 runs: cycles 3.137 → 3.111 G (-0.8%), instructions +0.8% | Below push’s gain, which step 16 took |
| The forward CSR built first, then the reverse one by transposing it, so the two place arrays are never live together (on step 15) | memory.peak, 6 runs: median 67.78 → 64.88 MB, highest 67.97 → 65.52. ab.py, 31 runs: median 130.61 → 137.06 ms, min 128.61 → 135.52. Build 34.5 → 42.7 ms (forward count 9.1, fault 3.6, scatter 10.9, sort 3.2; reverse count 3.1, fault 1.6, scatter 5.4, sort 3.5) | 2.9 MB saved for 6.5 ms: the queries’ own peak, about 64 to 65 MB, then caps the saving, and the second scatter costs more than pass 2 saves |
Step 17’s pass 3 in four rounds, each its own on_threads, with the sorted places given back between rounds | Not built in full: one on_threads of 12 threads that do nothing takes 172 to 189 µs (average of 20, three runs), so the forward direction’s three extra rounds cost about 0.55 ms | Step 17 frees as much with no extra rounds |
| Step 17 with each thread’s sorted blocks counted, and every block below 12 × the least count freed (on step 16) | memory.peak, 6 alternating runs: 62.1 to 62.5 against 63.9 to 64.3 MB | The same memory as step 17, which needs no list of block starts |
Csr::heavy_weight folded into unpack behind std::hint::cold_path(), as Csr::row does for wide groups, 3 lines fewer (on step 17’s code with step 18’s first cuts) | perf stat, 8 interleaved rounds: instructions 4,996 → 5,081 M (+1.7%), cycles 3,063 → 3,102 M (+1.4%), higher in all 8 | The hash lookup is laid out in the relaxation loop, where #[cold] keeps it out of line |
| Step 19’s pieces taken from the query counter by whichever thread is idle, in 2 MB or 8 MB pieces (one more line than step 19) | ab.py, 41 runs: 2 MB pieces -0.25%, -1.06%, -0.27% (seeds 1, 3, 2); 8 MB pieces -1.16, -1.12, -0.50, -1.09, -1.64, -1.04, -1.10, -0.83%; the same 8 MB claiming in its rustfmt-compliant form -0.41, +0.04, -0.78, -0.95, -0.94, -0.57, -0.84, -0.78% | No better than step 19’s fixed shares, for a line more |
The build’s faulting by madvise(MADV_POPULATE_WRITE) on 6 threads, with the runs set-up on the main thread at the same time (on step 18) | Phase marks, 11 runs: faulting and set-up together 4.5 → 10.6 ms, 1,700-2,250 page faults instead of 410 | The populate faulted 4 KB pages, not 2 MB ones |
No signal stack per thread: SIGSEGV and SIGBUS set to SIG_IGN from .init_array, before std’s runtime setup, so std gives no thread an altstack (on step 18 with step 19) | Phase marks, 11 runs: the build 36.21 → 36.00 ms, the queries’ end unchanged | 0.2 ms for about 9 lines |
| The queries on 6 threads instead of 12 (on step 18) | ab.py, 11 runs: 125.75 → 157.77 ms | Hyperthreading is worth 1.36× in the queries |
Pass 3’s blocks taken from a shared counter, each behind a Mutex, instead of dealt out in turn (on step 20, 4 more lines) | Phase marks, 21 runs: pass 3’s end 36.88 → 35.65 ms median, 34.55 → 34.58 fastest, the queries’ end 127.74 → 127.46. ab.py, 41 runs, median (min): seed 1 124.46 (122.38) → 124.06 (122.76), seed 3 133.28 (129.82) → 136.08 (130.39) ms | The last block ends sooner, but the run does not |
| The build’s faulting as 2 MB pieces taken from a shared iterator by 6 threads, instead of 6 fixed shares (on step 20, same line count) | Phase marks, 21 runs: faulting 3.57 → 3.43 ms median, 3.45 → 3.13 fastest, idle 3.20 → 1.87 ms·cpu. With the pass 3 counter above, ab.py, 41 runs: seed 1 124.70 (122.99) → 124.28 (122.14), seed 3 130.81 (128.17) → 130.25 (127.90) ms | The zeroing is bound by memory bandwidth, so balance saves little: -0.4% for 4 lines |
on_threads spawning as a tree: each new thread hands half of its items to another new thread (on step 20) | Phase marks, 21 runs: pass 3’s last thread starts 28.85 → 32.25 ms, the build ends 35.18 → 38.02, the run 124.31 → 126.89 ms | Each level waits for a new thread to wake up |
The rows faulted in on the main thread instead of 2 threads, and on_threads running its first item on the calling thread (on step 20, 2 more lines) | ab.py, 41 runs: seed 1 124.07 (121.96) → 124.00 (122.28), seed 3 130.05 (128.90) → 129.88 (128.21) ms | No gain: thread start-up is not what the phases wait for |
Each line’s separators found at once by a 32-byte compare (LLVM makes it vpcmpeqb and vpmovmskb), so the next line’s start does not wait for the numbers (on step 20) | Phase marks, 21 runs: with the fallback as a cmov, pass 1 9.6 → 13.4 ms; as a second loop, pass 1 9.6 → 10.8 and pass 2 12.4 → 16.9 ms | The parse is bound by instruction count (step 12), and the mask is more instructions |
| Two or three queries per thread, advanced one step each in turn, so one query’s misses overlap the other’s (on step 20) | ab.py, 21 runs: 124.77 → 139.64 ms (two), 154.38 ms (three) | Slower |
| Each direction’s rows started on a 2 MB boundary inside an allocation 2 MB larger, so all their 2 MB pages can be huge pages (on step 20, 5 more lines) | PEBS: 45% of the 4 KB page walks are the rows prefetch, 19% the edges prefetch. perf stat, 3 runs: 4 KB walks 3.7 → 1.1 M, walk cycles 117 → 46 M, cycles 3.211 → 3.183 G. ab.py, 41 runs: seed 1 124.42 (122.06) → 123.19 (121.41), seed 3 130.54 (128.61) → 129.79 (128.12) ms. memory.peak, 8 alternating runs, medians: seed 1 62.5 → 63.1, seed 3 62.35 → 63.15 MB. With the edge arrays aligned too: 0.66 M walks, peak about 2 MB higher | Each array’s last 2 MB page becomes a huge page as well, so +0.7 MB, which with 5 lines cancels the -0.8% |
| Both directions’ rows in one allocation and both edge arrays in another, so that glibc’s header of the second array no longer sits inside a 2 MB page, which then cannot be huge (on step 20, 2 more lines) | perf stat, 3 runs: 4 KB walks 5.1 → 0.87 M, cycles 3.2445 → 3.2425 G. ab.py, 41 runs: seed 1 125.18 (122.68) → 125.58 (123.15), seed 3 130.83 (128.42) → 132.23 (129.21) ms | Fewer walks, no faster |
| glibc’s mmap threshold raised to 32 MB once the build is done, so the label tables come from the threads’ arenas, whose 2 MB pages can be huge pages (on step 20, 1 more line) | perf stat, 3 runs: 4 KB walks 5.2 → 4.2 M, cycles 3.199 → 3.186 G. memory.peak, 4 alternating runs: 62.1 to 62.3 → 66.1 to 68.6 MB | The arenas keep the tables a table outgrew, and the queries then peak 4 to 6 MB above the build |
#[inline(always)] on Search::step again, now that push is inline (on step 20) | ab.py, 41 runs: seed 1 124.37 (122.81) → 126.25 (123.74) ms | Slower |
Every function aligned to 64 bytes (-C llvm-args=-align-all-functions=6), to keep line cuts from moving the hot loops (on step 17 and on step 18) | perf stat, 8 interleaved rounds: cycles +16.1 M (step 17’s code) and +12.9 M (step 18’s), +0.4 to 0.5%, higher in all 8 | step then starts on a line, which is slower than 16 bytes past one |
sort’s degree count and prefix sum as for_each calls, 4 lines fewer (on step 17) | Same machine code | Pedantic clippy’s needless_for_each rejects both; the prefix sum went in as a fold instead |