Performance¶
This is the reference for what the engine costs and how those numbers were obtained. It has four parts: the workloads, the measurement method, the current stage breakdown, and the ledger of every optimization that was attempted.
Three rules keep it honest:
- A number lives in one place. Reasoning about why a design is fast is in Low-Latency Design. Measurements that have been superseded are in Performance History. Nothing is restated.
- An effect is claimed as a range from paired runs, or not at all. This host varies by about +-22% between runs, so an unpaired comparison smaller than 5% means nothing. Several ledger rows below read "no measurable effect", and that is a result, not a failure to report.
- Behavior is pinned before speed is claimed. Every change below was accepted only after the invariant list in section 3.4 came back byte-identical.
1. Workloads¶
Four inputs are used. W1 is the latency target; the others exist to catch behavioral regressions.
W1: L2 incremental replay (primary)¶
Deribit BTC-PERPETUAL, one day of trades merged with an incremental depth stream. This is the workload every latency number below refers to.
./out/build/linux-debug/toy_quant l2_replay \
data/v2/crypto/deribit_trades_2020-04-01_BTC-PERPETUAL.csv.gz \
data/v2/crypto/deribit_incremental_book_L2_2020-04-01_BTC-PERPETUAL.csv \
BTC-PERPETUAL 0 active_l2 1 conservative --no-output --fast-validation
The full depth file is 1.5 GB and 11.4M batches, which is slow to iterate on, so two slices of the same file are used for day-to-day work:
| Slice | Rows | Batches | Events | Use |
|---|---|---|---|---|
/tmp/depth_200k.csv |
200,000 | 117,288 | 236,524 | quick correctness check |
/tmp/depth_2m.csv |
2,000,000 | 1,183,894 | 1,303,131 | stage timings |
Both are head -n prefixes of the full file, so they are the same data at different lengths, not
different data. The 200k slice is small enough that everything stays in page cache.
The shape of this feed is the reason the book container dominates the design discussion: 1.71 level updates per batch, more than a thousand live levels per side, and a live price span of about 20,000 ticks.
W2: Binance L1 replay (regression)¶
The line the project started with, kept as a regression workload. Its feed has no depth, so a resting order
there has no queue in front of it and a fill is a price event rather than a queue event. The run pins the L1
invariants that tools/gate/verify_l2.sh fast compares on every change, and the history of the line — what it
could and could not answer, and why the queue model moved to the L2 path — is in
Performance History.
./out/build/linux-debug/toy_quant replay \
data/v2/fixtures/test_aggTrades_5k.csv data/v2/fixtures/test_bookTicker_5k.csv BTCUSDT 0 optimized 1000000
W3: Legacy CSV plus backtest (regression)¶
./out/build/linux-debug/toy_quant csv data/scenarios/flat_ticks.csv 0 optimized
./out/build/linux-debug/backtest_main data/scenarios/flat_ticks.csv \
data/runtime/orders.csv data/runtime/trades.csv 0 0 backtest logs/backtest.log
W4: strategy benchmark (regression)¶
/usr/bin/time -f '%e' ./out/build/linux-debug/strategy_benchmark \
--trades=data/v2/fixtures/test_aggTrades_5k.csv \
--quotes=data/v2/fixtures/test_bookTicker_5k.csv --symbol=BTCUSDT --quantity-scale=1000000
2. Environment¶
- Linux x86_64 under WSL2, Intel Core Ultra 7 258V, 8 online CPUs.
- CMake preset
linux-debug, which isCMAKE_BUILD_TYPE=Debugplus the project's-O2 -march=native, and Debug adds-g. /usr/bin/timeis available.perfandvalgrindare not.gprofneeds the separatelinux-relwithdebinfopreset, andStageProfilerreplaced it for routine work.- WSL2 puts the page cache and the CPU governor outside the repository's control. Treat every absolute number as a property of today's machine, and every paired difference as a property of the code.
3. How to measure on this host¶
Nine subsections of method: the noise floor, paired alternation, wall clock against user time, the invariant list a change must not move, stage timing, why isolation benchmarks mislead, the fast loop, how a document's numbers are checked, counting what a profiler cannot see, and the hand-off between two threads. They are the answer to "how do you know"; a reader who wants only "how fast" needs section 4 and the ledger.
The method, one subsection per rule
3.1 The noise floor¶
Repeated runs of an unchanged binary on W1 spread over roughly +-22%. On the 1.5 GB workload the spread is larger still, because the wall clock then tracks whether the file is in page cache. Two consequences follow, and both are load-bearing:
- A single run cannot resolve anything below about 5%. Any claim in this document that rests on one run is labeled as such.
- Absolute numbers are not comparable across sessions. Only a ratio measured in the same session
is. The measured spread on W1 for one unchanged binary is
read+parsep50 of 581 ns in one session and 834 ns twenty minutes later, a 1.4x difference, with every stage's share unchanged.
3.2 Paired alternation¶
tools/bench/ab_bench.sh does this. It runs the two builds in ABBA order within a block, takes the paired
difference per block, and reports each stage's mean difference with its t statistic. Three things were
learned by pointing it at a null pair, meaning the same binary on both sides:
- The first run of a block is slower, and ABBA assigns that position to A, which biases every
result toward B. Running one binary as both A and B produced differences of -5% to -13% on every
stage with
tup to 3.6 until a discarded warm-up run was added at the start of each block. - The floor of the protocol is about 15%, not
t = 2.8. Four null comparisons of one binary against itself, five blocks each, produced per-arm differences of up to 13% with|t|never above 2.0, and the sign changed between sessions. Randomising which label receives the outer ABBA positions did not reduce it, so most of it is noise rather than a position effect. With five blocks the per-arm standard error is around 7%, so effects below roughly 15% are not claimable here, whatever theirt. - Two blocks are not enough. A null pair at two blocks reached +12% on the wall clock and -9% on
strategy. - Measure the null in the same session. Pass
ctrland the harness runs an A-versus-A pair interleaved with the A-versus-B pair, so that session's artifact is visible next to the effect. An effect is only believed when it stands clear of the null measured alongside it.
The practical consequence is a rule about which changes are worth attempting: prefer changes whose mechanism predicts an effect larger than the floor, and do not ship a change whose only argument is a sub-floor measurement. An isolation benchmark can still justify a mechanism, and a byte-identical full-file run can still prove behavior, but neither of them is a speed claim.
Stage-level claims are stronger than end-to-end ones for the same reason a paired difference beats two medians: the stage isolates the code under test from the rest of the event. Every stage is printed, including the ones that were not supposed to move, because a change confined to one stage that moves another is a measurement problem rather than a result.
Building the pair for a comparison, when the change under test is one or two files:
cp out/build/linux-debug/toy_quant /tmp/tq_after
git stash push -- path/to/changed/files
cmake --build out/build/linux-debug --target toy_quant
cp out/build/linux-debug/toy_quant /tmp/tq_before
git stash pop
cmake --build out/build/linux-debug --target toy_quant
cmp out/build/linux-debug/toy_quant /tmp/tq_after # the rebuild must reproduce the after binary
The last cmp matters: it proves the pair differs only in the stashed files. Piping a compiler's
output into head can raise SIGPIPE and leave a stale binary in place, which silently invalidates a
measurement by making both builds identical.
3.3 Wall clock, user time, and I/O¶
On W1 the wall clock is dominated by reading 1.5 GB, so a CPU change disappears into page-cache
noise. %U from /usr/bin/time isolates the CPU. The difference between the two is why the
full-file rows of the ledger look smaller than the slice rows: the same change, measured with the
I/O still in the figure.
3.4 The invariants that must not move¶
Every change is verified against these before any timing is taken. They cover all four workloads, so a change to the book container cannot silently alter the L1 path, and vice versa.
| Workload | Invariant |
|---|---|
| W2 (L1) | submitted_orders=13734 trade_reports=2277 fill_rate=0.175872 realized_pnl=-33.7861 equity=966.196 |
| W1, 200k slice | incremental_batches=117288 submitted_orders=406 trade_reports=1 queue_ahead_consumed=55460 realized_pnl=-0.002 equity=1000 |
| W1, full file | incremental_batches=11403032 submitted_orders=26145 trade_reports=222 realized_pnl=-1.0615 equity=998.939 |
| W3 | equity=1000.13 max_drawdown=2.49569e-05 |
| All | ctest green, zero new compiler warnings |
The strongest check available for a change that touches the book or the engine is to diff the whole stdout of a W1 run against a stored copy:
./out/build/linux-debug/toy_quant l2_replay ...args... > /tmp/full_after.txt 2>&1
diff -q /tmp/full_before.txt /tmp/full_after.txt
Byte-identical output over 11,403,032 batches is what "behavior preserving" means here, and it says more than any unit test can.
3.5 Stage timing¶
--profile-stages turns on StageProfiler, which times eight regions per event on every 64th event.
The profiler reads the clock twice at construction and subtracts the minimum of those reads from
every sample (35-50 ns here), because otherwise each region would be charged for a clock read and the
column sum would come out larger than the wall clock.
./out/build/linux-debug/toy_quant l2_replay ...args... --no-output --fast-validation --profile-stages
It works with --feed-thread as well, and then there are two reports: each thread has its own profiler, the feed
prints read+parse and validate and the consumer the six stages after them, and a stage a thread never brackets prints
as zero samples. The two blocks are a split of one event rather than two events. That is what makes the threaded path
measurable per stage at all — [LATENCY] counts in microseconds and the hand-off it would have to show is 170 ns. A
two-book run still refuses the combination, because there one profiler would be written by two pipelines as well.
Median of three runs each way on the W1 slice, one session, p50 in nanoseconds:
| stage | direct | threaded: feed | threaded: consumer |
|---|---|---|---|
read+parse |
793 | 774 | — |
validate |
74 | 94 | — |
book-apply |
81 | — | 124 |
market-view |
105 | — | 134 |
top-booking |
40 | — | 48 |
engine |
138 | — | 156 |
queue-acct |
8 | — | 10 |
strategy |
57 | — | 70 |
| column sum | 1284 | 868 | 542 |
Two things are worth taking from it, one structural and one measured.
The split is the thing threading buys. The feed thread carried 57–68% of the direct block's per-event work, so most of an event's cost is the reader's and it now runs beside the strategy instead of in front of it. That is the justification for the ring existing, and it is the first time this repository has shown it per stage.
Every stage came out slower than the same stage done serially, and the consumer's are the worse half: book-apply
+53%, market-view +28%, top-booking +20%, engine +13%, strategy +23%, and even the feed's validate +27%. The
ordering held across all three runs; the magnitudes did not, and this session was a noisy one — the consumer's column sum
was 290, 542 and 607 across the three, so treat the percentages as a direction rather than a size. The direction is the
useful part: the hand-off costs more than the 119 ns §3.9 measures, because that bench hands over a value the consumer
already has in cache, while a real event is written on one core and read on another. It is also one more reason not to
spend a restructuring on the event's type to recover 119 ns of it.
Reading the output:
- The numbers depend on the sampling interval.
read+parsemeasures 381-445 at interval 1, 414-551 at 64 and 435-686 at 512, and the sweep gives the same order in both directions, so it is not drift. With a large interval the profiler's own per-stage arrays are cold when a region is timed, and those misses are charged to the region. Interval 1 is the cleanest and the slowest to run; the tables in section 4 use 64, so their absolute values carry roughly 20% uncertainty from this alone. - The stage profiler and gprof are not comparable. gprof runs on RelWithDebInfo with
-pgand NDEBUG; the stage profiler runs on the Debug build with asserts live, which is whatctestneeds. In one sessionread+parsemeasured 566 ns under RelWithDebInfo and 651 ns under Debug, while the unprofiled wall clock differed by only 3%. Stage figures may be compared within one build and one session, never across. - Use the
p50column, and use share as a ranking. The mean is unusable for stages with rare stalls:read+parsereaches tens of microseconds at p999 because one sample can absorb a page fault or a 1 MiB block refill. Those samples move the mean by hundreds of nanoseconds and leave the median where it belongs. - The p50 column sum lands within 10-15% of the per-event wall clock, so the eight regions cover essentially the whole event. Treat the sum as a ranking tool and the wall clock as the absolute figure.
- Repeating a stage measurement three times and taking the median of the p50 values costs seconds and removes most of the run-to-run spread. Section 4 does exactly that.
- The probe is larger than some of the stages it reports, and the tool prints the figure it used.
Every run says
[PROFILE] clock overhead 45 ns per region, already subtractedon its own line. Three runs of the 2M slice in one session gave 45, 46 and 54 ns, so the correction moves by about 20% between runs — as large as the whole reported value ofqueue-acct(1-10 ns on those runs), and a tenth ofvalidate(68-78) andbook-apply(76-91).queue-acctandtop-booking(14-32) are therefore at or below the instrument's resolution: their p50 is the residual after subtracting a quantity of the same size as itself, and it should be read as "approximately zero, not resolvable at this interval" rather than as a cost. What the instrument does resolve isread+parse(717-731) andengine(136-144);validate,book-apply,market-viewandstrategysit at two to three times the floor, so their ranking is stable while their p50 carries a large relative error. Note that those figures are one session's, and the drift §2 warns about applies: they are not comparable with section 4's table, which was taken on a different one. The relationship is the point, not the values. The floor could be lowered —rdtscpcosts a fraction of asteady_clockread, and a region timed once per block of N events amortises one read over N — and neither is done here on purpose: every paired row in the ledger was measured through this instrument, and replacing it would make the record incomparable with itself.
3.6 Why isolation benchmarks mislead¶
Standalone microbenchmarks exist for the line layer, the field split, the number conversion, the container choice, the mutex, and the string hash. They are useful for one thing: answering a mechanism question. The string hash bench is the clean example. It measured
string key: find(s) then [s] = v 23.8 ns
string key: find(s), reuse iterator 13.7 ns
integer key: find(k) then [k] = v 10.5 ns
and the 10.1 ns between the first two lines is one hash, which settles a question the source could
not: operator[] re-hashes the key it was just given rather than reusing the hash from find. That
is a mechanism answer, and it is the only kind of answer this bench can give.
It is misleading for priority questions, and this project has the receipts:
- A line-layer benchmark pointed at field splitting as the next target, because that was all it could see. Stage timing later showed the field split is a small part of the parser's cost.
- A container benchmark said a book lookup would be 3.9x faster. The stage did improve by 70%, and the end-to-end effect was 6-10%.
- An allocation-based explanation ("161 ns per batch must be
malloc") was wrong: construction and moves dominated it.
The rule that came out of this: microbenchmarks nominate the next candidate, stage timing and paired end-to-end runs decide whether it ships.
3.7 The fast loop¶
Verifying every edit with the full-file comparison would make one iteration cost about a minute, so the checks are split by what they are for:
| Tier | Command | Cost | Purpose |
|---|---|---|---|
| 0 | ctest --preset linux-debug (inside fast) |
~3 s | The unit tests, because a red test must not be able to pass the gate |
| 1 | bash tools/gate/verify_l2.sh fast |
~1-2 min | The L2 200k and L1 invariants plus the numbers quoted in the documents, on every edit |
| 2 | bash tools/gate/verify_l2.sh full |
~26 s | The full-file stdout hash against the stored reference, before accepting |
| 3 | bash tools/gate/verify_l2.sh asan |
~10 s built, ~10 min cold | The same tests and one short replay under AddressSanitizer and UndefinedBehaviorSanitizer |
Measured on 2026-11-16 on eight cores with nothing else running, and the same numbers the header of
tools/gate/verify_l2.shcarries: tier 0 is 3 s, tier 2 is 26 s, and tier 3 is 6 s of tests plus 4 s of replay on a tree that is already built, against 632 s when the sanitizer tree is cold.code(tier 0 and the code half) is 26 s, so almost all of afastis its document half, about 1.5 min.allhas no row because it is the sum rather than a tier, and quoting it as one number is what made the previous version of this table wrong. A single number would be wrong forfasttoo: five runs on this host gave 70 s and 1 min 47 s, so the table says 1-2 min and the spread is stated rather than averaged away.What the document half is made of, measured page by page: the whole set is 107 s, and it is two pages --
history-03-studies.mdat 65 s andhistory-04-the-fee-is-not-the-wall.mdat 44 s -- which reconciles with the set within a run-to-run spread of about half a minute. The eight equity replays on part 4 are about five seconds each, not the thirty-five a previous version of this note claimed: that figure came from a slower host. On 2026-11-16 the equity studies moved to part 4 for exactly this reason, and the measured effect is that a prose edit to part 3 costs 65 s rather than 107 s whilefastis unchanged, becausefastruns every page.
Tier 1 compares batch counts, order and fill counts, realised PnL and consumed queue position, which is
what a reader or book change can actually break. Tier 2 is what makes a timing claim defensible,
because byte-identical output over 11.4M batches rules out every explanation except cost. The full-file
reference is kept as a hash, so tier 2 costs one 1.5 GB run instead of two, and ref re-records it
when a change is accepted.
Checking the numbers in the documents¶
A document that quotes replay output is a claim about the code, and this project's claims are its
product. Hand-copied claims drift: one did, a "thirty times per fill" that a re-measurement turned
into ten. Comparisons are therefore emitted by tools/sweep/compare_runs.sh --markdown, which prints the
table and a toyquant:check block carrying the exact command and the values it produced.
python3 tools/gate/check_docs.py docs/PERFORMANCE_HISTORY.md docs/ARCHITECTURE.md docs/DESIGN_REVIEW.md docs/PERFORMANCE.md
That re-runs each recorded command and fails when a quoted number has moved. Only marked blocks are
checked, so prose that records history under conditions which no longer exist is left as it was, and
a table is checked exactly when someone decided it should be. A block may also name the binary it runs,
binary: ring_bench, which is resolved beside the binary the gate passes in: that is how a benchmark that
is not the main binary is checked at all (§3.9 is the one such block), and a block whose command exits
non-zero fails, because a binary that crashed printed none of the values the block is about.
Two more things keep the loop short:
-
The measured lever matrix is one command.
bash tools/sweep/workload_matrix.sh [placement|requote|model|arrival]runs each lever around the same window and prints the fill counts, the per-contract edge and the fees, so the ordering recorded inPERFORMANCE_HISTORY.mdcan be reproduced rather than trusted. -
Build one target while iterating. A change to a header such as
tick_ladder.his included by eight targets, so a plaincmake --buildrebuilds all of them: 25 steps instead of 2. Usecmake --build out/build/linux-debug --target toy_quant, then run the whole build plusctestonce when accepting the change. - Let the harness do the pairing.
bash tools/bench/ab_bench.sh <binaryA> <binaryB> [blocks]runs ABBA blocks and prints the per-stage paired difference. It prints every stage, including the ones that were not supposed to move, which is how a measurement problem is told apart from a result. It also regenerates the data slices when/tmphas been cleared.
3.8 Counting what a profile cannot see¶
A function level profile samples the program's own text, so a call that resolves into a shared library
looks like a leaf with no body: the call appears, its cost does not. tools/bench/count_libc_calls.c is an
LD_PRELOAD shim that interposes the few calls that matter for a market data reader and reports counts,
byte totals and a size histogram.
gcc -O2 -shared -fPIC -o /tmp/count_libc_calls.so tools/bench/count_libc_calls.c -ldl
LD_PRELOAD=/tmp/count_libc_calls.so ./out/build/linux-debug/toy_quant l2_replay ... 2>&1 | grep SHIM
Counting is cheap and timing each call would not be, since a clock read costs more than some of the calls. The tool therefore answers "how many, and what shape" and leaves the per-call cost to the isolation benches. On the 2M slice, per event over 1,303,131 events:
| Call | Per run | Per event | Shape |
|---|---|---|---|
memchr |
28,549,312 | 21.9 | 1.5 calls at n~1 MiB are the line scan, ~13.5 at n<=256 are the eight comma searches per row |
memcpy |
11,629,137 | 8.9 | 8.0 of them at n<=16 bytes |
read |
279 | 0.0002 | 156 MB in 1 MiB blocks |
Two things follow. The requested byte totals must not be read as work: memchr stops at the first
match, so the 1.1 TB this shim printed on its first outing was the sum of the lengths asked for, not
the bytes touched, and it nearly sent the search in the wrong direction. And the calls are too few and
too short to be the cost: 22 memchr and 9 memcpy per event is what a 77 byte row with eight fields
should produce, and 279 read calls for a 154 MB input is one per megabyte.
With /usr/bin/time -v reporting 3.4% system time, zero major page faults and 8 MB peak RSS, this is
what closed the search for a hidden cost in the reader.
3.9 The hand-off between two threads¶
The live path runs the feed on one thread and the strategy on another, joined by concurrency::SpscRing.
What that hand-off costs is a mechanism question the replay's [LATENCY] line cannot answer, because a
replay reports the feed's parsing and the strategy's decisions in the same window. ring_bench is the
isolation bench for it: one producer thread, one consumer thread, both running the same loop N times, so
the per-message number is the pair's sustained pace rather than one call's latency.
cmake --build --preset linux-relwithdebinfo --target ring_bench
python3 tools/study/ring_bench_table.py # three sessions of `ring_bench 2000000 5`, medians
The table below is that tool's output on this host. The case labels are the benchmark's own rows; the payload rows carry a prebuilt value unless the label says it is built per message.
| case | ns/op | session spread | M ops/s |
|---|---|---|---|
| empty round trip, 1 thread, uint64 | 2.26 | 2.1-3.2 | 442.5 |
| full ring, refused push | 0.45 | 0.4-0.7 | 2222.2 |
| stream uint64, 2 threads, ring 4096 | 18.29 | 17.0-29.0 | 54.7 |
| stream 16 byte POD, prebuilt | 19.28 | 16.9-32.6 | 51.9 |
| stream 128 byte POD, prebuilt | 30.85 | 26.1-64.3 | 32.4 |
| stream POD the event's size, prebuilt | 50.37 | 47.9-78.5 | 19.9 |
| stream trade event, prebuilt | 142.90 | 137.0-158.2 | 7.0 |
| stream trade event, built per message | 169.92 | 169.4-214.2 | 5.9 |
| stream book batch, built per message | 239.38 | 237.2-240.8 | 4.2 |
| stream uint64, 2 threads, ring 8 | 59.08 | 59.0-60.4 | 16.9 |
| stream trade event, mutex + condvar | 301.35 | 297.9-310.1 | 3.3 |
| stream trade event, mutex, consumer spins | 320.52 | 303.4-326.6 | 3.1 |
Two invocations of that tool are enough to see the limit of the table: across two sets of three sessions the event-sized POD row read 50.4 and then 57.8 ns, and the trade event built per message read 169.9 and then 175.5, while the ratios between the rows barely moved. Everything below is therefore about ratios, and the absolute figures are this host's on the day the tool was run.
Three findings, and the second is the one that was not expected. The mechanism is not the cost. A push and a pop on one thread round trip in 2.26 ns and a refused push against a full ring costs 0.45 ns, so the publication -- one release store paired with an acquire load, the two lines of code the ring's whole contract rests on -- is a couple of nanoseconds of a two digit number. Whatever the two-thread rows are paying for, it is not the atomics.
The payload is the cost, and its type matters more than its size. A trivially copyable payload of
exactly the event's size -- 296 bytes, pinned to sizeof(MarketEvent) by a static_assert in the
benchmark -- hands over in 50.37 ns, while the real MarketEvent, a std::variant whose active member
carries two std::strings, takes 142.90 ns. The event's non-trivial move and destructor cost about 93 ns,
which is more than the 296 bytes they move: every message runs a variant move into a slot and a variant
destructor out of it. Building the event per message adds 27 ns for a trade and 96 ns for a two-update book
batch on top of that. This is the lead the numbers leave: a trivially copyable event of the same size would
be handed over at 2.8x the rate, which is a change to the event type rather than to the ring.
A lock costs more than a wake-up. Against the pattern most code reaches for -- a std::deque behind a
mutex, with a condition variable waking the consumer per message -- the ring is 1.8x faster for this payload
(169.92 against 301.35 ns/message). The same queue with the consumer spinning on the lock instead of sleeping
costs 320.52 ns, so the wake-up is not the price of the lock: the mutual exclusion is. A 1.8x margin is
smaller than "lock-free" sounds, and it is the honest one for the event this path actually carries. The
ring's capacity shows up in the same table: the uint64 stream through an 8 slot ring costs 59.08 ns against
18.29 through 4096, because a ring too small for the burst makes the producer wait for room.
Read all of it as a property of this host. Nothing is pinned to a core, the machine is a hybrid eight-core laptop under WSL2, and the two-thread rows moved by up to 1.5x between sessions -- which is why the table carries the session spread rather than one figure, and why no gate asserts a nanosecond. What the gate does re-derive is the one thing about the benchmark that a broken ring would change:
That is a 200,000-message run: it has to report the message count it was given, the payload size it is measuring, and the checksum every one of those values produced while crossing. A ring that dropped a value, reordered two, or handed over a slot that was still being written would change the checksum and fail the gate, whatever it did to the clock.
4. Current stage breakdown¶
Median of three --profile-stages runs on the 2,000,000-row slice: 20,361 samples over 1,303,131
events, with every change in this document applied.
| Stage | Share (p50) | p50 | p90 | p99 | p999 |
|---|---|---|---|---|---|
| read+parse | 61.1% | 528 | 654 | 897 | 21840 |
| validate | 5.3% | 46 | 81 | 145 | 340 |
| book-apply | 5.9% | 51 | 100 | 166 | 414 |
| market-view | 11.1% | 96 | 153 | 230 | 526 |
| top-booking | 1.3% | 11 | 53 | 96 | 215 |
| engine | 13.1% | 113 | 159 | 275 | 1647 |
| queue-acct | 0.5% | 4 | 25 | 54 | 141 |
| strategy | 4.2% | 36 | 89 | 157 | 2935 |
| column sum | 100% | 864 |
Rows that moved because of the work in this document: book-apply from a p50 of 193 to 51, engine
from 167 to 113, market-view from 96 to 68, and read+parse down a further 11% since this snapshot
was taken. The read+parse share rose from about 50% to 61% partly because the other stages shrank.
Read the Share column, not the absolute ones. This snapshot is one machine state. The host drifts:
the same unchanged binary measured read+parse at 581 ns in one session and 834 ns twenty minutes
later, a 1.4x spread, while every stage's share stayed within a percentage point. Absolute values here
describe a session, and only the paired deltas in the ledger travel between them.
The two smallest rows are below the instrument's resolution, not small in the way the others are: see
§3.5, where queue-acct and top-booking are explained as approximately zero rather
than as costs. The Share column is what they are good for, and it is the column this table is written for.
5. Optimization ledger¶
One row per attempt, including the ones that did not pay. "Effect" is a paired measurement unless noted otherwise. The mechanism behind each accepted row is explained in Low-Latency Design.
| Change | Mechanism | Verified effect | Status |
|---|---|---|---|
| Buffered line reader | 1 MiB blocks, memchr line boundaries, string_view into the block |
-0.258 s (-16.0%) end-to-end, W1 2M slice, 9 pairs; -10.2% with output on. Line layer alone 0.115 -> 0.080 s (1.44x) | kept |
TickLadder book container |
one flat array indexed by price tick instead of a red-black tree | book-apply p50 193 -> 51; in-process book 1085.3 -> 804.3 ns/batch (-25.9%); end-to-end -9.5% (200k slice, t=-2.83), -6.0% (2M slice), -6.8% (full file, %U) |
kept |
| Symbol id registry in the engine | per-symbol state keyed by integer instead of by symbol string | engine p50 141 -> 111 (-21.3%), 5/5 pairs, t=-2.85; engine mean -31.7% |
kept |
| Single-pass top-level walk | one bounded walk per side produces the touch and the depth sum, instead of nth(0)..nth(4) restarting from the best slot each time |
market-view p50 95.7 -> 68.4 ns (-28.5%), 5/5 pairs, t=-25.3; column sum -46.4 ns (-5.7%); end-to-end wall clock -5.9%, t=-2.61; read+parse and book-apply unchanged as controls; output byte-identical over 11,403,032 batches |
kept |
| Reader micro-optimizations | four inline update slots per batch, column-role jump table, parse_boolean first-character dispatch |
no measurable effect: ABBA paired mean +5.4 ns, SE 12.4, over four blocks on a ~530 ns stage | kept, unproven |
Fast path for parse_uint64 |
two digits per step with the validation folded into the loop, for values of at most 18 digits, plus the cold throwing path moved out of the hot function | read+parse p50 -44.8 ns (-9.2%), 5/5 pairs, t=-6.2; column sum -67.3 ns (-8.4%); end-to-end wall clock -6.0%, t=-4.49; output byte-identical over 11,403,032 batches |
kept |
Sorted std::vector for the book |
binary search, plus memmove on insert |
1.02-1.11x over the map, in isolation | rejected |
| Integer-plus-scale price parse | parse the price with integer arithmetic instead of the out-of-line std::from_chars<double> in libstdc++ |
read+parse p50 -65.5 ns (-11.3%), 5/5 pairs, t=-5.9, reproduced at -71 ns in a second session; end-to-end wall clock -7.6%, t=-2.83; output byte-identical over 11,403,032 batches |
kept |
| Fixed-point price parsing | integer-only price path in the reader | rejected on an isolation comparison (17 ns vs 10 ns) whose in-context cost is about 48 ns per call | superseded by the row above |
| Removing the book mutex | drop the lock from L2OrderBook |
4.2 ns of a ~1200 ns event (0.7%) | rejected, lock kept |
Growth margin 1024 to 256 in TickLadder |
how many slots a growth adds at each end of the covered tick range | not resolvable: 5 ABBA blocks with a null control moved book-apply +16.7% (t=1.44) and market-view +13.2% (t=1.46), which the margin can touch, and also validate +15.7% (t=1.53) and read+parse +9.2% (t=1.13), which read a file and cannot be touched by it; the null pair was positive on every stage (+2% to +16%) and no t-statistic reached the 2.8 this ledger uses. The knob was checked for capacity-only first: both margins print byte-identical stdout on the 200k slice (2947 bytes), and tools/bench/count_libc_calls.c reports identical counts in every bucket, so neither instrument can see a growth on this workload. |
rejected, kept at 1024 |
| SPSC ring for the feed hand-off | bounded single-producer ring: one release store paired with an acquire load, indices on separate cache lines, values placement-newed into slots | isolation bench (§3.9), not a paired run: 2.26 ns for a push+pop round trip, 18.29 ns/message for a two-thread uint64 stream, and 1.8x the mutex + condition variable hand-off for the event it carries (169.92 against 301.35 ns/message) | kept |
| Hand-off through a mutex + condition variable | std::deque behind a mutex, one wake-up per message |
301.35 ns/message for the same payload and the same per-message construction, 1.8x the ring | rejected |
| Hand-off through a mutex with the consumer spinning | the same queue with no sleeping, to separate the wake-up from the mutual exclusion | 320.52 ns/message: the exclusion is the cost, not the wake-up | rejected |
| An 8 slot ring to bound the burst earlier | capacity small enough that the producer usually finds the ring full | 59.08 ns/message against 18.29 at 4096 slots, so 4096 is not an oversized default | rejected |
| Interned symbol handle on the L2 quote path | L2MarketView and BboQuote carry a 16-byte SymbolName -- an id and a pointer into an intern table -- instead of a std::string, so the name is constructed once per run rather than six times per event, and the engine keys on symbol.id() without hashing at all; its own symbol_ids_ registry, and the second id space that came with it, are gone |
not resolvable on this host, and pointing the wrong way: five ABBA blocks with the null control measured in the same session moved top-booking +79.4% against a +69.8% null, strategy +17.1% against +14.3%, engine −3.8% against a +5.0% null, and the end-to-end wall clock −0.6% (t = −0.12); output byte-identical over 11,403,032 batches |
kept, unproven: what it removes is a duplicate registry, and the copies it removes were cheaper than the estimate that motivated them |
Where each attempt is argued¶
The numbers are the table above; the mechanism behind them is in Low-Latency Design, one section per design, and each of its sections opens with the ledger row it explains. This is the same pairing read from the other end, so a row can be found without scanning that document:
| Section of the design record | The rows above it argues |
|---|---|
| 1. The line layer | the buffered line reader |
| 2. The book container | TickLadder, the single-pass top-level walk, and the growth margin |
| 3. Per-symbol state | the symbol id registry, and the interned symbol handle |
| 4. The instrument | none — it is the StageProfiler that the rows above were measured with |
| 5. The number conversions | the integer-plus-scale price parse, and the parse_uint64 fast path |
| 6. The hand-off | the ring, and the capacity that bounds it |
| 7. Measured and rejected | the sorted vector, the first price parse, the word-at-a-time split, the book mutex, both mutex hand-offs, and the reader micro-optimizations |
Resolution¶
Read the numbers above with the floor in section 3.2 in mind: at five blocks
the per-arm standard error is about 7%, so a stage effect below roughly 15% is not claimable on this
host, and the t values in the table come from runs taken before the positional bias and the warm-up
were understood. What is certain for every accepted row is the byte-identical full-file comparison and
the mechanism; the magnitudes of the two smallest rows, the price fast path and the parse_uint64 fast
path, are direction-confirmed but not resolved. The two reader fast paths measured together against the
state without them gave read+parse -24% with a same-session null of +1.6%, which is above the floor
but whose staging was contaminated: engine and market-view, which the change cannot touch, moved
-25% and -19% in the same run.
Session total¶
The three changes added in the session that produced the price, parse_uint64 and market-view rows
measure -16.1% on the column sum and -11.9% on the end-to-end wall clock (t = -4.60, 4/4 pairs)
against the state before them.
Their individual end-to-end estimates were -7.6%, -5.9% and -6.0%, which compound to about -18%. The measured total is smaller, which is the usual result: each change removes a fraction of what remains, so the later ones have less left to take. Individual paired effects are not additive, and only the cumulative measurement settles the total.
What the ledger says¶
Of ten attempts, six moved a stage by at least 8%, one changed no measurable number at all, one could not be resolved, and two were rejected — one of them wrongly, which is now recorded as superseded. Six predictions were made and five of them were wrong:
| Prediction | Measured |
|---|---|
| Rewriting the price parse without the general purpose double parser is not worth it | wrong, and it cost the largest remaining single win. The isolation comparison said 1.7x; the in-context cost is ~48 ns per call, and removing it is -11% of read+parse |
| An ablation that removes one call measures that call | wrong by 4x. Collapsing the price to two values also shrank the whole run's memory footprint, so its 259 ns was ~65 ns of parse plus ~194 ns of cache effect |
| A sorted vector beats a tree slightly, so the tree's pointer chasing is the cost | 1.02-1.11x: both structures pay for the same shape |
| The mutex on the book is worth removing | 4.2 ns, 0.7% |
| "161 ns per batch" is allocation cost | it was construction and moves |
| Ten string lookups on the engine hot path should cost ~55 ns | ~30 ns: the isolation bench measures a dependency chain, and the real loop overlaps the hash with other work |
Cost intuition on this codebase is systematically off by 3-10x, always in the same direction. That is the most reusable finding in this document, and it is why the ledger exists as a table of attempts rather than a list of wins.
The last four rows are a different kind of entry from the ones above them: they are isolation bench measurements of a two-thread hand-off, so they have no stage share and no end-to-end effect to report, and the counts in the paragraph above describe the paired rows only.
6. Where the remaining time is¶
read+parse is 61% of the event, and the last two attempts to reduce it both measured as no effect.
That is the useful conclusion: the remaining cost is not in the micro-structure of the row loop,
and further tuning there has now been tried twice and paid nothing.
- The "unattributed half" of
read+parsedoes not exist, and finding that closed the question. An earlier reading said gprof accounted for only half ofread+parseand that the rest sat in invisible library code. That comparison was invalid twice over: gprof runs on RelWithDebInfo with-pgand NDEBUG while the stage profiler runs on the Debug build with asserts live, and the two were measured in different sessions. Counting the candidates directly ruled them out, per event over 1,303,131 events: 279readsyscalls per run (156 MB) with 3.4% system time, 0 major page faults and 8 MB peak RSS; 22memchrand 9memcpycalls, all short, the longestmemchrbeing the single line scan each row already needs; and removing onemalloc/freepair per batch was measured as no effect earlier in the ledger. I/O, syscalls, page faults and hidden library calls are each too small to be worth attacking. What is left inread+parseis our own code, and it is close to its floor: the number conversions were the two real levers and both are gone, and the field split measured within 12% of a hand-tuned word-at-a-time scan. The one shape change left is parsing a block in bulk instead of a row at a time, and the question that decides it is whether reordering the work can beat a loop that is no longer doing anything obviously wasteful. market-view: done, and the stage is now about 8% of the event. The single-pass walk landed (ledger above). What remains inside the stage is twoprice_from_tickconversions, the arithmetic, and the sixteen byte handle the view now carries instead of a copy of the name. The 1024-slot growth margin was the fourth candidate here, and it has been measured: the margin is capacity only — both values print byte-identical stdout on the 200k slice — and on this workload neither the ABBA harness nor the libc shim can see a growth, so what would settle it is a workload with more ladder growths rather than a better clock (the ledger row above).engine, 13%. What remains is not lookups. Each batch copies aBboQuoteintolatest_quotes_,l2_top_bbo_andexternal_bbo_, andMEOrderBookstill uses astd::mapper price level. The name in that struct is an interned handle now, so the copies that are left carry one SSO string (exchange) and sixteen bytes of symbol rather than two strings — measured, and worth nothing (the ledger's interned-symbol row). The book-container result in the ledger is the argument for measuring aTickLadderinMEOrderBooktoo, and counting settles it without a measurement: this strategy posts 406 orders over 117,288 batches, and the most any setting reached was 685 (--refresh-price-ticks=1 --edge-cover-ticks=0) and 682 (--base-spread-ticks=1 --refresh-price-ticks=1). At one or two resting levels a side, astd::mapcosts tens of nanoseconds per own order — a few tens of microseconds in a run — so the container is not a latency item at this order flow, and manufacturing more of it would mean a strategy the project does not have.validate(5%) andstrategy(4%) stay out of scope until the three above are settled.
Those four are the whole of what is left, and each is stated with the measurement that would settle it, because that is the only thing that would move any of them. Two of the four are closed rather than open.
The reader is at its floor. The number conversions were the two real levers in read+parse and both are
gone (the ledger above); the field split measures within 12% of a hand-tuned word-at-a-time scan; and the
three candidates for a hidden cost — syscalls, page faults and library calls — were counted directly and
ruled out in §3.8. What remains there is our own code doing its own work, so the only shape change that
could still matter is reading the block in bulk rather than a row at a time, and that is a question about
reordering work rather than about waste.
The instrument cannot resolve the small stages, and it now says so. §3.5 states the probe cost and the
rows it is larger than, so queue-acct and top-booking are read as approximately zero rather than as
costs. That closes the last loose end in this document: the numbers that could not be trusted carry their
caveat, and the two that can be trusted up here are named.
What is left for a later session is therefore a choice rather than a search, and the choice has narrowed to one item that
counting retired rather than measured: MEOrderBook's std::map per level is not a latency item at this order flow. The
engine bullet above gives the three counts — 406 orders at the recorded setting, 685 with the refresh threshold at a
tick and the fee gate off, 682 at the touch — and one or two resting levels a side puts the container at tens of
nanoseconds per own order, a few tens of microseconds in a run. Manufacturing more order flow would mean a strategy this
project does not have, and the conservative quoter is not an accident: it is the finding.
The growth margin was the other, and it has now been measured and could not be resolved. That is a result of a different kind from the ones above and worth keeping in the same place: the knob is inert enough that this workload cannot price it, which is more useful to a later session than leaving it as an untuned constant with a plausible story attached.
The event's shape, and why it is not being changed. §3.9 leaves one number
standing: the ring hands over MarketEvent at 169.9 ns/message against 50.4 for a trivially copyable payload of exactly
the same size, so about 119 ns per event is the move and destructor of two std::strings and a std::vector. Nothing
else in this document points at a larger single item.
Three measurements, not preferences, say no. The last attempt at the same family of copies — six std::string copies and
two hashes per event, replaced by an interned handle — measured as nothing at all (the ledger row), which is the estimate
that has been wrong most often here being wrong again: an SSO copy lives in a cache line the event already touches. The
119 ns is a type cost the ring pays per message rather than a copy, but it exists only on the --feed-thread path, and
no recorded number in this repository comes from that path: the gate runs one threaded run to assert it reports what the
direct run reports, and nothing else is measured there. And it is not a rename — MarketDepthSnapshot carries two
std::vector<DepthLevel>, so a trivially copyable event means either a fixed bound on a snapshot's levels, which is a
behaviour change on the workload that uses snapshots, or a pooled buffer with a return protocol, which is a different
concurrency contract than "the ring owns the value".
What would change the verdict is a recorded run measured in threaded mode whose conclusion depends on its throughput. The profiler can now be pointed at that path (§3.5), so the next session can take the measurement instead of arguing about it; until then the answer is the one the last experiment gave.