Repository navigation
perf: take std::function, a re-tested word skip and two mask rounds off the hot paths - #112
Merged
Merged
Conversation
…ff the hot paths Five measured changes on the maxspeed profile, plus the cleanup they made possible. Every figure is instructions/op under Callgrind (bench/run_callgrind.sh), which is what this repo measures with because it is deterministic and machine-independent. Workload before after delta encode: u64 array (1000) 38 046 35 046 -7.9 % encode: typical message 266 224 -15.8 % decode: u64 array (1000) 44 839 43 830 -2.2 % decode: typical message 1 329 1 199 -9.8 % 1. dispatchLevel took its per-field callback as `const std::function&`, so every `read()` of a sub-message built one, invoked through it twice and destroyed it through its manager pointer; the std::function machinery was ~13 % of the `decode: typical message` profile. It is now a template on the callable. The two call sites pass a stateless no-op and a two-pointer lambda. 2. utf8Valid re-tested its eight-byte ASCII-skip condition once per character, so a short ASCII payload paid four branches a byte -- validating the five-byte string of the shared `typical message` workload cost ~62 instructions. The word skip and the byte scan now each run to completion before the other is considered. 3. spread7's last two rounds are spelled as an add. Once the 7-bit groups are laid out, each round's two halves partition the live bits, so `(w & keep) | ((w & move) << k)` is exactly `w + (2^k - 1) * (w & move)` -- one mask and one OR less per round, three x86 instructions off every varint the encoder writes. 4. getVarintWindowed took its single-byte fast path off a separate byte load of p[0] before loading the eight-byte word it needs anyway; the test now comes off that word. The tenth-byte overflow test `(b & 0x7f) > 1 || (b & 0x80)` folds to `b > 1`, which is the same predicate. 5. The float scalar/array paths built their four or eight wire bytes with a shift loop that GCC did not fold into a store. New detail::storeLittleBits / loadLittleBits keep the byte-at-a-time form for big-endian hosts only. Cleanup in the same pass: - The field-header parser existed twice, at the top level and inside a sequence, and the copies had already drifted once: the nested one shipped without the §6.2 ARRAY_MAX ceiling on a fixlen array's count word until #103. They are now one parser (parseFieldTag + parseFieldMeta, composed by parseFieldHeader for the top level, which owns the dangling-SequenceEnd rule). 70 lines gone. - headerParsersEnforceCeilings() can now assert the invariant at full strength -- exactly one site decodes a field header -- instead of checking that each of however many sites happens to carry the ceilings. - Dropped a doc block for a function that no longer exists, and moved the wire() documentation back onto wire() (it sat on consumed()). Behaviour is unchanged, and the two rewrites that could plausibly change it are pinned by differential tests against independent references: - utf8ValidatorSweep() (new) compares utf8_valid against a direct transcription of Unicode Table 3-7 over ~45 000 cases: every byte value and every interesting multi-byte sequence at every offset 0..17 inside an ASCII run, so each atom in turn crosses, starts on and ends on an eight-byte boundary. It passes unmodified against the pre-change header. - varintWidthSweep() already pins spread7/gather7 byte-exactly against a reference varint over every width, both boundaries of every width and a pseudo-random spread, windowed and byte-at-a-time. Full suite green in Debug and Release under GCC 15 and Clang, under ASan+UBSan, and against all 81 shared vectors plus the 11 invalid_utf8 ones.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
One consolidated optimization-and-cleanup pass on the maxspeed profile. Every
change in it has a number; two that measured neutral were tried and dropped
rather than committed.
Measurements
Instructions/op under Callgrind —
bash bench/run_callgrind.sh, the deterministic,machine-independent figure this repo's head-to-head table is built on. Same host,
same
-O3build, before =main@ fe0df0a.Raw before / after tables
bench(MB/s) andperf(cycles/op) both still run and move the same way, butthis host's wall-clock spread on the array rows is ±10 % run to run, so they are
not the evidence — the Ir table is.
What moved, and why
Each item was found by
callgrind_annotateon the workload it shows up in, andre-measured on its own.
1.
std::functionin the nested-dispatch path (−81 Ir ondecode: typical,together with the parser fold below).
dispatchLeveltook its per-fieldcallback as
const std::function&, so everyread()of a sub-messageconstructed one, invoked through its
_M_invokerafter an emptiness test, anddestroyed it through its manager pointer. The
std_function.hlines were ~13 %of the workload's profile. It is now a template on the callable; the two call
sites pass a stateless no-op (
skipPayload) and a two-pointer lambda (read),so the instantiation count is bounded and the body inlines into both.
2.
utf8Validre-tested its word-skip condition per character (−42 Ir onencode: typical, ~−60 ondecode: typical). The loop asked "are eight bytesleft?" once per byte, so a short ASCII payload paid four branches per character:
validating
"sofab"cost ~62 instructions, a quarter of the wholeencode: typical message. The word skip and the byte scan now each run tocompletion before the other is considered.
3.
spread7's last two rounds are an add (−3 000 Ir onencode: u64 array,exactly 3 instructions per element). Once the 7-bit groups are laid out, each
round's two halves partition the live bits —
w == (w & keep) + (w & move)exactly — so
(w & keep) | ((w & move) << k)isw + (2^k − 1) * (w & move).That drops one mask and one OR per round. The first round cannot use it (it
would need
wpre-masked to 56 bits in a register of its own, which costs backmore than it saves). Verified equivalent over 20 M random values plus every
single-bit and every low-mask input before it went in, and pinned in-tree by the
existing
varintWidthSweep().4.
getVarintWindowed's single-byte peel (−1 000 Ir ondecode: u64 array).It read
p[0]separately, then loaded the eight-byte word it needs anyway. Thetest now comes off that word. Also
(b9 & 0x7f) > 1 || (b9 & 0x80)folds tob9 > 1— the legal tenth bytes are0x00and0x01and nothing else, so it isthe same predicate in one compare.
5. Float scalar/array byte loops. The four or eight wire bytes were built
with a shift loop GCC did not fold into a store. New
detail::storeLittleBits/loadLittleBitsmemcpy on little-endian and keep the byte-at-a-time form forbig-endian hosts only.
Tried, measured neutral, not included
msb * 9 + 73to fold the+1into theconstant: identical instruction count (GCC already emits
bsr; xor $0x3fand aleaeither way).error_ | limitExceeded_instead of||in the top-level loop: 1 198 → 1 198.I did not touch
topCallback_. Replacing it with a function-pointer sink saves~60 Ir on
decode: typical, but it makesIStreamInline— the documentedcallback surface — one indirect hop worse, and the only way to keep the bench
honest about that is to pay the same hop in the bench adapter. Trading one public
path's cost for another's is not a win.
Cleanup in the same PR
parseTopLevel, oncecopied into
dispatchLevel— and the copies had already drifted: the nestedone shipped without §6.2's
ARRAY_MAXceiling on a fixlen array's count worduntil fix(decode): a schema bound outranks the reassembly cap (#86) #103 put it back. They are now one parser:
parseFieldTag(the headerword and
ID_MAX) plusparseFieldMeta(§4.6's fixlen word, §4.7/§4.8's countand element word,
ARRAY_MAX), composed byparseFieldHeaderfor the toplevel, which owns the one rule that is the top level's own — a dangling
SequenceEndis INVALID there and the close inside a sequence. 70 linesdeleted, with the check order in both loops byte-for-byte what it was.
headerParsersEnforceCeilings()can now state the invariant at fullstrength: it asserts there is exactly one site that decodes a field header,
instead of checking that each of however many sites happens to carry the
ceilings. A second copy is a regression whether or not it is complete on the
day it appears.
wire()documentation moved back onto
wire()(it had come to sit onconsumed()).Why behaviour is unchanged
The two rewrites that could plausibly change behaviour are pinned by differential
tests against independent references, not by inspection:
utf8ValidatorSweep()(new) comparesutf8_validagainst a directtranscription of Unicode Table 3-7, sharing no code, table or loop shape
with it, over ~45 000 cases: every one of the 256 byte values and 26 crafted
multi-byte sequences (valid edge, overlong, surrogate, out-of-range, truncated,
bad-continuation) placed at every offset 0..17 inside an ASCII run with 0..17
trailing bytes — so every atom in turn crosses, starts on and ends on an
eight-byte boundary, and every truncation distance is covered. Plus ASCII runs
of every length 0..64. It passes unmodified against the pre-change header,
which is the point: it asserts the behaviour, not the rewrite.
varintWidthSweep()(already in tree) pinsspread7/gather7byte-exactly against a reference varint encoder over every width, both
boundaries of every width and a pseudo-random spread, in the windowed and the
byte-at-a-time paths.
Verified locally:
ctestgreen in Debug and Release, under GCC 15 and Clang.test_roundtripsuite and the shared-vector suite green underASan + UBSan (
-fno-sanitize-recover=all) — relevant becausegetVarintWindowednow takes its eight-byte load before the single-bytebranch; its callers all guarantee the documented
VARINT_MAX_BYTESwindow.invalid_utf8vectors, byte-exact.SOFAB_STRICT_UTF8=0) still compiles clean, andutf8_validstill evaluates in a constant expression (static_assert),including a surrogate reject at a 16-byte offset.
The big-endian legs of
storeLittleBits/loadLittleBitsare the byte loopsthey replaced, unchanged; no ppc64 cross toolchain is available here, so CI's
QEMU leg is what confirms them.
README
The
Instruction counts (Callgrind)table's last column is updated to the newfigures. The two C columns are the earlier joint run's — only this library's code
moved, and I cannot re-run
corelib-c-cpp's script — so the prose now saysexactly that instead of continuing to claim all four were measured together.