From 403d0e8b98708cc2b7bc156f466c1411e4be206a Mon Sep 17 00:00:00 2001 From: Andreas Steinbart Date: Sun, 9 Aug 2026 10:59:58 +0000 Subject: [PATCH] bench: the datasets, rows and grammar BENCH_SPEC actually asks for MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The suite measured four rows of BENCH_SPEC's eleven. The three it never ran are not incidental: `blob 1MB` is the only workload in the spec that reaches CORELIB_PLAN §5.1's divisible-run path, `composite` is the only one that touches a wrapper array, non-ASCII UTF-8, depth-3 nesting, an omitted all-default field or a two-byte field header, and `composite skip-all` is the only one that measures the walk-and-materialize-nothing path §7.2 item 7 requires be tested. Adds all six missing rows, driven through the API as it now is: the one-shot `blob` row writes into a caller buffer sized by hand (the schema is unbounded, so a generated MAX_SIZE would be the configured ceiling, not a bound), the streaming row installs a 4096-byte buffer with a flush sink and no pass-through permission, and the decode row is fed in 4096-byte chunks with `reset()` between messages so the reassembly capacity is kept instead of re-acquired. The composite decode reads into heap-free destinations, so no allocator traffic lands in a figure that is meant to be the decoder. What the new rows say, in Ir/op: encode: blob 1MB one-shot 1 000 026 decode: blob 1MB 3 654 639 encode: blob 1MB streaming 13 009 127 decode: composite 22 417 encode: composite 11 514 decode: composite skip-all 7 671 The one-shot/streaming gap is 13x — 13 instructions per payload byte against one. `pushBytes` takes a memcpy when the run fits the buffer and a byte-at-a-time `pushByte` loop when it does not, and a megabyte through 4096 bytes is entirely the second case. Under MB/s the same gap reads 43x (42 064 against 970), but that row is bandwidth-bound and the Ir figure is the one to quote. Two supporting changes: * The entry points are `flatten` as well as `noinline`. GCC's inlining budget is TU-wide, so growing the file from four workloads to ten moved `encode: typical message` from 224 Ir/op to 330 and `decode: typical message` from 1199 to 1355 without the library changing a line. Flattened, the four pre-existing workloads measure identically at four workloads and at ten (226 / 1275 / 35 044 / 43 839), a couple of percent above what an unconstrained GCC finds for a small file. A figure that is stable across releases is worth more here than one that is minimal; the README table is updated to the flattened readings. * `test_bench_tools` now holds the tooling against BENCH_SPEC rather than only against itself: the published set is the spec's, every label matches its output grammar, both printed tables match it row for row, and the cross-port parity sizes hold (`blob 1MB` 1 000 005, `composite` 956, `perf` 170). It drives the real loops over a token budget through `SOFAB_BENCH_SECONDS`, which exists for that check alone — the default stays BENCH_SPEC's ~1 s. The Ir table's title becomes "pure-C++20" to match the label `bench` and `perf` already print; plain "C++" is corelib-c-cpp's wrapper column. --- README.md | 96 +++++++++-- bench/CMakeLists.txt | 13 +- bench/bench.cpp | 333 ++++++++++++++++++++++++++++++++++++-- bench/bench_common.hpp | 48 +++++- bench/run_callgrind.sh | 2 +- bench/test_bench_tools.sh | 173 ++++++++++++++++++-- 6 files changed, 616 insertions(+), 49 deletions(-) diff --git a/README.md b/README.md index 1bf1710..c320ca3 100644 --- a/README.md +++ b/README.md @@ -717,12 +717,16 @@ Five suites run under CTest: off that one parse; since the envelope is generated upstream and has grown a top-level key before, each walker demands its own key and the run fails loudly when it is absent, renamed or empty, instead of quietly testing nothing. -- **`test_bench_tools`** — guards the benchmark tooling's single sources of - truth (see [Benchmarks](#benchmarks)): every workload `bench --list` publishes - runs and reports its size, an unknown name is rejected, neither - `run_callgrind.sh` nor `bench/CMakeLists.txt` keeps a second copy of the - workload list, and `bench.cpp`/`perf.cpp` take the stream adapters and the - timing harness from `bench_common.hpp` rather than redeclaring them. It also +- **`test_bench_tools`** — guards the benchmark tooling against BENCH_SPEC and + against internal drift (see [Benchmarks](#benchmarks)): the published workloads + are BENCH_SPEC's, all of them and none outside its output grammar; both printed + tables match that grammar row for row; the cross-port parity sizes hold + (`blob 1MB` 1,000,005, `composite` 956, `perf` 170); every workload + `bench --list` publishes runs and reports its size; an unknown name is + rejected; neither `run_callgrind.sh` nor `bench/CMakeLists.txt` keeps a second + copy of the workload list; and `bench.cpp`/`perf.cpp` take the stream adapters + and the timing harness from `bench_common.hpp` rather than redeclaring them. + It also drives `run_callgrind.sh` end to end against a stub `valgrind`, so it needs no Valgrind and still proves a failing measurement aborts the table with the captured diagnostic. Skipped when the build did not produce the `bench` binary. @@ -769,9 +773,12 @@ cmake --build build --target doc ## Benchmarks -Two tools mirror the C / C++ / Rust / Go / Java / Python benchmarks on identical -workloads (a 1000-element `u64` array and a typical mixed message), so results -are directly comparable across languages: +Three tools mirror the C / C++ / Rust / Go / Java / Python benchmarks on +identical workloads, so results are directly comparable across languages. The +workloads are BENCH_SPEC's four datasets — a 1000-element `u64` array, a +`typical` mixed message, an unbounded **1 MB `blob`**, and a `composite` message +that exercises what the flat three never reach (a wrapper array, multi-byte +UTF-8, depth-3 nesting, a field the encoder must omit, a two-byte field header): ```sh cmake -S . -B build -DCMAKE_BUILD_TYPE=Release @@ -794,6 +801,31 @@ cmake --build build --target run_bench_callgrind # the same script, driven from Those figures are the head-to-head data below. +On this machine (GCC 15, `-O3`, x86-64) the throughput table reads: + +``` +encode: u64 array (1000) 4295.75 decode: u64 array (1000) 3529.74 +encode: typical message 2051.08 decode: typical message 377.27 +encode: blob 1MB one-shot 42063.92 decode: blob 1MB 16696.61 +encode: blob 1MB streaming 970.19 decode: composite 539.41 +encode: composite 922.58 decode: composite skip-all 1705.72 +``` + +Two of those rows are not a statement about this library. Five bytes of the +`blob 1MB` message are metadata and a million are payload, so its MB/s is the +host's `memcpy` and its memory bandwidth — **read the one-shot and streaming +rows against each other, never either alone.** Their difference is what +CORELIB_PLAN §5.1's divisible-run path costs, and it is stark: 42.1 GB/s in one +contiguous write against 0.97 GB/s through a 4096-byte buffer with a flush sink, +**43×**. The instruction counts below put the same gap at **13×** with bandwidth +taken out of it — the encoder's `pushBytes` takes a `memcpy` when the run fits +the buffer and falls back to a byte-at-a-time loop when it does not, and a +megabyte through 4096-byte buffers is entirely the second case. Nothing else in +the suite reaches that path: the other three datasets are schema-bounded and +small enough that no flush happens mid-encode. `blob 1MB passthrough`, +BENCH_SPEC's optional third row, is absent because this port implements no +pass-through permission. + All three tools measure **one** list of workloads: the table in `bench/bench.cpp`, published by `bench --list` as `namelabel` lines and read from there by `run_callgrind.sh` and the CMake target, so a workload cannot be renamed in one @@ -808,7 +840,12 @@ build/bench/bench --list # the workloads, one "namelabel" per lin build/bench/bench encode_typical # one operation, then exit (Callgrind mode) ``` -`ctest -R test_bench_tools` guards that sharing. +`ctest -R test_bench_tools` guards that sharing, and holds both printed tables +against BENCH_SPEC's output grammar and its two cross-port parity sizes +(`blob 1MB` = 1,000,005 bytes, `composite` = 956, as `perf`'s message is 170). It +drives the real loops over a token time budget via `SOFAB_BENCH_SECONDS`, which +exists for that check alone — nothing that publishes a number changes it, and +the default is BENCH_SPEC's ~1 s per workload. ### Choosing between the two C++ corelibs @@ -844,9 +881,9 @@ is better). All three are compiled at `-O3` so the comparison is like-for-like: | Workload | C | C++ wrapper | this (pure C++20) | |---|--:|--:|--:| | encode: u64 array (1000) | 124 992 | 125 021 | **35 046** (−72 %) | -| encode: typical message | 908 | 1 008 | **224** (−75 %) | -| decode: u64 array (1000) | 289 941 | 289 942 | **43 830** (−85 %) | -| decode: typical message | 2 057 | 2 056 | **1 199** (−42 %) | +| encode: typical message | 908 | 1 008 | **226** (−75 %) | +| decode: u64 array (1000) | 289 941 | 289 942 | **43 839** (−85 %) | +| decode: typical message | 2 057 | 2 056 | **1 275** (−38 %) | The four columns were measured together on one machine and the percentages are against the C column. The last column has since been re-measured on its own — @@ -854,6 +891,39 @@ only this library's code moved — and is the current reading; the two C columns are the joint run's. Reproduce with `bash bench/run_callgrind.sh` here and the same script in `corelib-c-cpp`. +The two message rows read 224 and 1199 before the suite grew to BENCH_SPEC's +full ten workloads, and the library did not change: GCC's inlining budget is +per-translation-unit, so a bigger `bench.cpp` was enough to move them (to 330 and +1355, in fact, before the entry points were marked `flatten`). `flatten` pins +each Callgrind toggle point to its own call tree, which is what makes a figure +comparable from one release to the next; the four rows above then measure +identically whether the file holds four workloads or ten, at a couple of percent +above the absolute minimum an unconstrained GCC finds for a small file. That +trade is deliberate — a stable number is worth more here than a minimal one. + +The six BENCH_SPEC rows this table does not compare (no C figures exist for them +yet) round the picture out: + +| Workload | Ir/op | bytes | +|---|--:|--:| +| encode: blob 1MB one-shot | 1 000 026 | 1 000 005 | +| encode: blob 1MB streaming | 13 009 127 | 1 000 005 | +| encode: composite | 11 514 | 956 | +| decode: blob 1MB | 3 654 639 | 1 000 005 | +| decode: composite | 22 417 | 956 | +| decode: composite skip-all | 7 671 | 956 | + +The `blob 1MB` pair is the one to read together: **13× more instructions** to put +the same megabyte through a 4096-byte buffer with a flush sink than to write it +contiguously — 13 instructions per payload byte against one. That is the whole +cost of CORELIB_PLAN §5.1's divisible-run path here, and it comes from +`pushBytes` falling back to a byte-at-a-time `pushByte` loop the moment the run +does not fit the buffer; the one-shot row takes the `memcpy` branch and pays a +single instruction per byte. Nothing else in the suite reaches that fallback. +`decode: composite skip-all` is the other pair-wise reading: walking the message +and materialising nothing costs **7 671** against **22 417** to decode it, so +about two-thirds of a decode is the destinations rather than the parse. + The encode figures include the §2 sequence hold-back — the price of never framing an all-default sub-message, see [Sequence framing](#sequence-framing-an-all-default-sub-message-is-omitted). diff --git a/bench/CMakeLists.txt b/bench/CMakeLists.txt index d76c2b8..e3494ce 100644 --- a/bench/CMakeLists.txt +++ b/bench/CMakeLists.txt @@ -29,11 +29,14 @@ if(VALGRIND_EXECUTABLE) add_dependencies(run_bench_callgrind bench) endif() -# The three tools stay comparable only while they share one definition of the -# workloads, the stream adapters and the timing rules. This checks that sharing -# structurally, and drives `bench --list` plus run_callgrind.sh end to end (with a -# stub valgrind, so it needs no Valgrind and runs in milliseconds). +# BENCH_SPEC fixes the workloads, their parity sizes and the output grammar, and +# CORELIB_PLAN §10 requires all three tools to follow it from one definition of +# the workloads, the stream adapters and the timing rules. This checks the +# published set against BENCH_SPEC, holds both printed tables against its +# regexes, checks the sharing structurally, and drives `bench --list` plus +# run_callgrind.sh end to end (with a stub valgrind, so it needs no Valgrind and +# runs in milliseconds). add_test(NAME test_bench_tools COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_bench_tools.sh - $ ${CMAKE_CURRENT_SOURCE_DIR}) + $ ${CMAKE_CURRENT_SOURCE_DIR} $) set_tests_properties(test_bench_tools PROPERTIES SKIP_RETURN_CODE 77) diff --git a/bench/bench.cpp b/bench/bench.cpp index 8db3cc9..f58a1ea 100644 --- a/bench/bench.cpp +++ b/bench/bench.cpp @@ -2,10 +2,25 @@ * @file bench.cpp * @brief SofaBuffers pure-C++20 — throughput benchmark (MB/s, CPU time). * - * Mirror of bench/c/bench.c and bench/cpp/bench.cpp: identical workloads, data, - * field ids and values, driven through the pure-C++20 implementation - * (include/sofab/sofab.hpp — no C backend), so the figures are directly - * comparable to the C corelib and its C++ wrapper. + * Mirror of bench/c/bench.c, bench/cpp/bench.cpp and corelib-rs/benches/bench.rs: + * identical workloads, data, field ids and values, driven through the pure-C++20 + * implementation (include/sofab/sofab.hpp — no C backend), so the figures are + * directly comparable to the C corelib, its C++ wrapper and every other port. + * + * BENCH_SPEC's four datasets: a 1000-element `u64` array, a small mixed + * `typical` message, an unbounded 1 MB `blob`, and the `composite` message that + * exercises what the flat three never reach (a wrapper array, multi-byte UTF-8, + * depth-3 nesting, an omitted all-default field, a two-byte field header). + * + * **Read the `blob 1MB` rows against each other, not against the others.** Five + * bytes of that message are metadata and a million are payload, so its MB/s is + * this machine's `memcpy` and its memory bandwidth, not a statement about the + * corelib. The signal is the *difference* between the one-shot row (one + * contiguous write, no sink) and the streaming row (the same bytes through ~245 + * flushes of a 4096-byte buffer): that difference is the cost of CORELIB_PLAN + * §5.1's divisible-run path, and this is the only workload in the suite that + * exercises it at all. Read it as Callgrind `Ir/op` (run_callgrind.sh), where + * instruction counts do not care about bandwidth. * * Two modes: * bench -> timed MB/s table (default, CPU time). @@ -28,6 +43,16 @@ #define N 1000 +/*! `blob 1MB` payload length. The encoded message is BLOB_LEN + 5 bytes on every + * port — a 1-byte header `(1 << 3) | 2` and a 4-byte fixlen word + * `(1000000 << 3) | 3` — which BENCH_SPEC states as a cross-port parity check. */ +#define BLOB_LEN 1000000 + +/*! Buffer the streaming `blob 1MB` row encodes through, and the chunk size its + * decode row is fed in. A fixed 4096 on every port so the rows stay comparable; + * `MIN_OUTPUT_BUFFER` does not enter into it (it is at most 20). */ +#define BLOB_CHUNK 4096 + namespace { @@ -43,6 +68,35 @@ uint8_t typ_buf[256]; size_t typ_used; const uint16_t arr16[4] = {10, 20, 30, 40}; +/* `blob 1MB`: the payload, the one-shot output buffer, the 4096-byte streaming + * scratch, and the decode destination. All static, so no allocation lands in a + * measured run. */ +uint8_t blob_src[BLOB_LEN]; +uint8_t blob_enc[BLOB_LEN + 16]; +size_t blob_used; +uint8_t blob_scratch[BLOB_CHUNK]; +uint8_t blob_dec[BLOB_LEN]; +size_t blob_stream_used; /* bytes the streaming sink was handed, in total */ + +/* `composite`: encoded message and the pieces of its two payload fields. */ +uint8_t comp_buf[2048]; +size_t comp_used; + +/*! One cycle of the `composite` string field: 1-, 2-, 3- and 4-byte UTF-8 + * (`a`, `ä`, `€`, `𝄞`), spelled as bytes so no source encoding can change it. + * The literal is split at every escape boundary because a hex escape otherwise + * swallows the following hex digits. */ +const char kCompCycle[] = "a" "\xc3\xa4" "\xe2\x82\xac" "\xf0\x9d\x84\x9e"; +constexpr size_t kCompCycleLen = sizeof kCompCycle - 1; /* 10 bytes */ +char comp_text[kCompCycleLen * 32]; /* 320 UTF-8 bytes, id 2 */ + +/* The 64 elements of the wrapper array (id 1), "item-0" .. "item-63". + * Built once at startup: BENCH_SPEC's dataset is the *values*, and formatting + * them inside the measured run would put snprintf in a figure that is supposed + * to be the encoder. Longest is "item-63" (7 chars). */ +char comp_items[64][8]; +uint8_t comp_item_len[64]; + /* decode targets */ uint64_t dec_array[N]; struct Targets @@ -61,10 +115,82 @@ struct ChildMsg : sofab::IStreamMessage }; ChildMsg childMsg; +/* ---- `composite` decode destinations -------------------------------------- + * + * Heap-free throughout: an InlineVector of FixedString for the wrapper array, a + * FixedString for the 320-byte payload. A std::vector would put 64 + * frees and 64 allocations into every measured decode, which is the allocator's + * figure and not the decoder's. */ + +struct CompOut +{ + sofab::InlineVector, 64> items; /* id 1 */ + sofab::FixedString<384> text; /* id 2 */ + uint32_t deep = 0; /* id 3 → 1 → 1 → 1 */ + int32_t sig = 0; /* id 3 → 2 */ + uint32_t big = 0; /* id 130 */ +} C; + +/* id 3 is nested three levels deep, so it needs three readers: the hold-back run + * on the encode side has a matching descent on the decode side. */ +struct CompLevel3 : sofab::IStreamMessage /* { 1: unsigned 7 } */ +{ + void deserialize(sofab::IStreamImpl &s, sofab::id i, size_t, size_t) noexcept override + { + if (i == 1) s.read(C.deep); + } +} compL3; + +struct CompLevel2 : sofab::IStreamMessage /* { 1: { … } } */ +{ + void deserialize(sofab::IStreamImpl &s, sofab::id i, size_t, size_t) noexcept override + { + if (i == 1) s.read(compL3); + } +} compL2; + +struct CompLevel1 : sofab::IStreamMessage /* { 1: { … }, 2: signed -1 } */ +{ + void deserialize(sofab::IStreamImpl &s, sofab::id i, size_t, size_t) noexcept override + { + if (i == 1) s.read(compL2); + else if (i == 2) s.read(C.sig); + } +} compL1; + +/* The wrapper array's collector (MESSAGE_SPEC §5.1): one field header per + * element, the element id is the array index. Declared count 64, element maxlen + * 16 — the schema facts a generated reader would pass, and what sizes the + * heap-free destination above. */ +sofab::StringSeq compItems{C.items, 64, 16}; + +/* The `blob 1MB` decode row is fed in chunks, so its stream lives across the + * calls that make up one op — and across ops, deliberately. `reset()` is the + * message-loop call (it starts a new message but keeps the reassembly buffer's + * capacity), so a decoder that has run once does not re-acquire a megabyte for + * the next message. Constructing a fresh stream per op instead would put that + * megabyte of allocator traffic into every iteration and measure malloc. */ +IStreamRaw blobStream; + void make_src() { for (int i = 0; i < N; i++) src[i] = (uint64_t)i * 0x9E3779B97F4A7C15ULL; + + /* Same constant as the u64 array, low byte — one magic number in the suite, + * and the same derivation in every port. */ + for (size_t i = 0; i < BLOB_LEN; i++) + blob_src[i] = (uint8_t)((uint64_t)i * 0x9E3779B97F4A7C15ULL); + + for (size_t i = 0; i < sizeof comp_text; i++) + comp_text[i] = kCompCycle[i % kCompCycleLen]; + + for (int i = 0; i < 64; i++) + comp_item_len[i] = (uint8_t)snprintf(comp_items[i], sizeof comp_items[i], "item-%d", i); + + blobStream.init([](sofab::id id, size_t, size_t) { + if (id == 1) blobStream.read(blob_dec, sizeof blob_dec); + }); } void encode_typical(OStreamRaw &os) @@ -81,6 +207,69 @@ void encode_typical(OStreamRaw &os) os.sequenceEnd(); } +/*! + * The `composite` message (BENCH_SPEC), field by field and each for a reason: + * + * - **id 1** — the suite's only wrapper array (MESSAGE_SPEC §5.1): 64 string + * elements carrying one field header each, element id = array index, so ids + * 0–15 encode in one header byte and 16–63 in two. + * - **id 2** — 320 UTF-8 bytes covering 1-, 2-, 3- and 4-byte sequences, which + * puts the §6.4 validator on a payload that is not ASCII (its word-skip fast + * path does not apply). + * - **id 3** — nesting at depth 3, so the lazy hold-back run grows past the + * single level `typical` and `perf` reach. + * - **id 4** — equal to its declared default, so the encoder must *not* write + * it: `sequenceBeginLazy` + `sequenceEnd` with nothing in between is the + * hold-back's discard path, the one branch nothing else in the suite takes. + * - **id 130** — the suite's only two-byte field header, `(130 << 3) | 0`. + * + * Encodes to 956 bytes on every port (the reference implementation's figure), + * which is this dataset's parity check the way 170 is `perf`'s. + */ +void encode_composite(OStreamRaw &os) +{ + os.sequenceBeginLazy(1); + for (sofab::id i = 0; i < 64; i++) + os.write(i, std::string_view(comp_items[i], comp_item_len[i])); + os.sequenceEnd(); + + os.write(2, std::string_view(comp_text, sizeof comp_text)); + + os.sequenceBeginLazy(3); + os.sequenceBeginLazy(1); + os.sequenceBeginLazy(1); + os.write(1, static_cast(7)); + os.sequenceEnd(); + os.sequenceEnd(); + os.write(2, static_cast(-1)); + os.sequenceEnd(); + + /* id 4: all-default — opened and dropped, emitting nothing. */ + os.sequenceBeginLazy(4); + os.sequenceEnd(); + + os.write(130, static_cast(0xDEADBEEF)); +} + +/*! + * The streaming `blob 1MB` row's sink. BENCH_SPEC is explicit that it **consumes + * and discards**: accumulating the bytes would charge the streaming row a copy + * the one-shot row never pays, and I/O is not deterministic under Callgrind. + * Folding one byte per call is the minimum that keeps the call from being + * optimised away; the byte counter is what proves the row really moved a + * megabyte, and costs one add per flush. + * + * It returns without installing a buffer, which is §5.1's *copying* sink: the + * encoder resumes in the same 4096-byte buffer from offset 0. + */ +uint8_t blob_sink_acc; + +void blob_sink(std::span packet) noexcept +{ + blob_sink_acc ^= packet.empty() ? 0 : packet[0]; + blob_stream_used += packet.size(); +} + double measure(void (*fn)(), size_t bytes) { fn(); /* warmup */ @@ -89,9 +278,22 @@ double measure(void (*fn)(), size_t bytes) } // namespace -/* ---- workloads (extern "C" + noinline = stable Callgrind toggle points) --- */ - -extern "C" __attribute__((noinline)) void run_encode_u64_array() +/* ---- workloads (extern "C" + noinline = stable Callgrind toggle points) --- + * + * `flatten` on top of `noinline` is what keeps an Ir/op figure comparable from + * one release of this file to the next. Without it a workload's instruction + * count depends on how much *else* is in the translation unit: GCC's inlining + * budget is TU-wide, so growing the suite from four workloads to ten moved + * `encode: typical message` from 224 to 330 Ir/op and `decode: typical message` + * from 1199 to 1355 — up to a 47 % "regression" in a library that had not + * changed a line. `flatten` inlines each entry point's call tree, and the + * four pre-existing workloads then measure the same with ten workloads in the + * file as they did with four (verified: 226 / 1275 / 35 044 / 43 839 either + * way). The figures it reports are a hair above what an unconstrained GCC finds + * for a four-workload file, and that is the trade — a number that is stable is + * worth more here than a number that is minimal. */ + +extern "C" __attribute__((noinline, flatten)) void run_encode_u64_array() { OStreamRaw os; os.init(enc_u64_buf, sizeof enc_u64_buf); @@ -99,7 +301,7 @@ extern "C" __attribute__((noinline)) void run_encode_u64_array() enc_u64_used = os.bytesUsed(); } -extern "C" __attribute__((noinline)) void run_encode_typical() +extern "C" __attribute__((noinline, flatten)) void run_encode_typical() { OStreamRaw os; os.init(typ_buf, sizeof typ_buf); @@ -107,7 +309,7 @@ extern "C" __attribute__((noinline)) void run_encode_typical() typ_used = os.bytesUsed(); } -extern "C" __attribute__((noinline)) void run_decode_u64_array() +extern "C" __attribute__((noinline, flatten)) void run_decode_u64_array() { IStreamRaw is; is.init([&is](sofab::id id, size_t, size_t count) { @@ -116,7 +318,7 @@ extern "C" __attribute__((noinline)) void run_decode_u64_array() is.feed(enc_u64_buf, enc_u64_used); } -extern "C" __attribute__((noinline)) void run_decode_typical() +extern "C" __attribute__((noinline, flatten)) void run_decode_typical() { IStreamRaw is; is.init([&is](sofab::id id, size_t, size_t) { @@ -135,6 +337,84 @@ extern "C" __attribute__((noinline)) void run_decode_typical() is.feed(typ_buf, typ_used); } +/* `blob 1MB`, the floor: the whole message into a buffer sized by hand to hold + * it (1,000,005 bytes), no sink, so the payload is one contiguous write and no + * flush logic runs. The buffer is NOT taken from a generated MAX_SIZE — this + * schema declares no maxlen, so its MAX_SIZE would be the configured ceiling + * rather than a size the message cannot exceed (BENCH_SPEC). */ +extern "C" __attribute__((noinline, flatten)) void run_encode_blob_oneshot() +{ + OStreamRaw os; + os.init(blob_enc, sizeof blob_enc); + os.write(1, blob_src, (int32_t)BLOB_LEN); + blob_used = os.bytesUsed(); +} + +/* The same bytes through a 4096-byte buffer with a flush sink: ~245 flushes, + * and every one of them lands mid-payload, so this is the divisible-run path of + * CORELIB_PLAN §5.1 end to end. Pass-through is not granted — this port + * implements none, so BENCH_SPEC's optional `blob 1MB passthrough` row is + * omitted rather than printed as a placeholder. */ +extern "C" __attribute__((noinline, flatten)) void run_encode_blob_streaming() +{ + blob_stream_used = 0; + OStreamRaw os; + os.init(blob_sink, blob_scratch, sizeof blob_scratch); + os.write(1, blob_src, (int32_t)BLOB_LEN); + os.flush(); +} + +/* `blob 1MB` decode, fed in 4096-byte chunks: every chunk but the last ends + * inside the payload, so all but the last feed returns INCOMPLETE and the field + * is reassembled across them. `reset()` first — this is a new message on a + * stream that has already carried one (§5.1: a clean destination is the + * application's job), and it is what keeps the reassembly capacity. */ +extern "C" __attribute__((noinline, flatten)) void run_decode_blob() +{ + blobStream.reset(); + for (size_t off = 0; off < blob_used; off += BLOB_CHUNK) + { + const size_t n = blob_used - off < BLOB_CHUNK ? blob_used - off : (size_t)BLOB_CHUNK; + blobStream.feed(blob_enc + off, n); + } +} + +extern "C" __attribute__((noinline, flatten)) void run_encode_composite() +{ + OStreamRaw os; + os.init(comp_buf, sizeof comp_buf); + encode_composite(os); + comp_used = os.bytesUsed(); +} + +extern "C" __attribute__((noinline, flatten)) void run_decode_composite() +{ + IStreamRaw is; + is.init([&is](sofab::id id, size_t, size_t) { + switch (id) + { + case 1: is.read(compItems); break; + case 2: is.readString(C.text); break; + case 3: is.read(compL1); break; + case 130: is.read(C.big); break; + default: break; + } + }); + is.feed(comp_buf, comp_used); +} + +/* `decode: composite skip-all` — the path a router or filter runs: walk the + * message, materialize nothing. A callback that reads nothing declines every + * field, so the decoder skips each one by its metadata (and descends into the + * sequences to skip those too). Its distance from run_decode_composite is what + * not-decoding is worth here. */ +extern "C" __attribute__((noinline, flatten)) void run_decode_composite_skip() +{ + IStreamRaw is; + is.init([](sofab::id, size_t, size_t) {}); + is.feed(comp_buf, comp_used); +} + /* ---- the workload table: the one definition of what this suite measures --- * * The timed table, the single-shot Callgrind mode and `--list` all walk this @@ -155,13 +435,38 @@ struct Workload const size_t *bytes; /* message size, valid once setup+run have run */ }; +/* The `blob 1MB` decode row's setup encodes the input *and* runs one decode. + * The second is what makes the single-shot Callgrind figure the same operation + * the timed loop measures: the first decode grows the reassembly buffer to a + * megabyte, and collecting that one-off growth would report the allocator's + * cost as the decoder's on every port that reassembles. `reset()` keeps the + * capacity, so from the second call on there is none. */ +void setup_decode_blob() +{ + run_encode_blob_oneshot(); + run_decode_blob(); +} + const Workload kWorkloads[] = { {"encode_u64_array", "encode: u64 array (1000)", nullptr, run_encode_u64_array, &enc_u64_used}, {"encode_typical", "encode: typical message", nullptr, run_encode_typical, &typ_used}, + {"encode_blob_oneshot", "encode: blob 1MB one-shot", nullptr, run_encode_blob_oneshot, + &blob_used}, + /* The streaming row's size is what the sink was actually handed, so a row + * that did not move the whole megabyte fails the parity check instead of + * borrowing the one-shot row's figure. */ + {"encode_blob_streaming", "encode: blob 1MB streaming", nullptr, run_encode_blob_streaming, + &blob_stream_used}, + {"encode_composite", "encode: composite", nullptr, run_encode_composite, &comp_used}, {"decode_u64_array", "decode: u64 array (1000)", run_encode_u64_array, run_decode_u64_array, &enc_u64_used}, {"decode_typical", "decode: typical message", run_encode_typical, run_decode_typical, &typ_used}, + {"decode_blob", "decode: blob 1MB", setup_decode_blob, run_decode_blob, &blob_used}, + {"decode_composite", "decode: composite", run_encode_composite, run_decode_composite, + &comp_used}, + {"decode_composite_skip", "decode: composite skip-all", run_encode_composite, + run_decode_composite_skip, &comp_used}, }; const Workload *find(const char *name) @@ -186,8 +491,11 @@ int run_one(const char *name) if (w->setup) w->setup(); w->run(); - fprintf(stderr, "arr0=%llu f1=%u s_f2=%d str=%.5s BYTES=%zu\n", - (unsigned long long)dec_array[0], T.f1, T.s_f2, T.f5.c_str(), *w->bytes); + /* Every workload's result reaches an observable, so none of them can be + * optimised away between the toggle points Callgrind collects. */ + fprintf(stderr, "arr0=%llu f1=%u s_f2=%d str=%.5s blob=%u sink=%u items=%zu deep=%u BYTES=%zu\n", + (unsigned long long)dec_array[0], T.f1, T.s_f2, T.f5.c_str(), + blob_dec[BLOB_LEN - 1], blob_sink_acc, C.items.size(), C.deep, *w->bytes); return 0; } @@ -220,5 +528,6 @@ int main(int argc, char **argv) for (const Workload &w : kWorkloads) printf("%-26s %12.2f\n", w.label, measure(w.run, *w.bytes)); printf("\nMB = 1e6 bytes. ~1s CPU-time loop per workload.\n"); + printf("blob 1MB is bandwidth-bound: read one-shot vs streaming, not either alone.\n"); return 0; } diff --git a/bench/bench_common.hpp b/bench/bench_common.hpp index 52f5c18..61d8cb4 100644 --- a/bench/bench_common.hpp +++ b/bench/bench_common.hpp @@ -18,6 +18,7 @@ #include #include +#include #include #include @@ -44,6 +45,19 @@ class OStreamRaw : public sofab::OStreamImpl { public: void init(uint8_t *b, size_t n) noexcept { initBuffer(b, n, 0); } + + /*! + * A caller-supplied buffer installed **with a flush sink** — CORELIB_PLAN + * §5.1's streaming half, and the only configuration in which a message + * larger than the buffer can be encoded at all. `encode: blob 1MB streaming` + * is the workload that drives it (BENCH_SPEC), through a buffer of exactly + * 4096 bytes. + */ + void init(flushCallback cb, uint8_t *b, size_t n) noexcept + { + flushCallback_ = std::move(cb); + initBuffer(b, n, 0); + } }; class IStreamRaw : public sofab::IStreamImpl @@ -71,6 +85,26 @@ inline uint64_t cycles() noexcept /*! Process CPU time in seconds (not wall-clock). */ inline double cpu_now() noexcept { return (double)std::clock() / (double)CLOCKS_PER_SEC; } +/*! + * @brief How long one measured loop runs, in CPU seconds. + * + * BENCH_SPEC fixes this at ~1 s and that is the default; nothing that publishes + * a number changes it. The environment override exists for the one caller that + * is not after a number — `test_bench_tools.sh`, which holds the printed tables + * against BENCH_SPEC's output grammar and would otherwise spend a minute of CI + * producing figures it discards. Driving the real loop over a token budget keeps + * that check on the same code path as the real run. + */ +inline double loopSeconds() noexcept +{ + static const double v = [] { + const char *e = std::getenv("SOFAB_BENCH_SECONDS"); + const double d = e ? std::atof(e) : 0.0; + return d > 0.0 ? d : 1.0; + }(); + return v; +} + /* Block size for the timed loop: enough iterations that one clock reading is a * rounding error against them. std::clock() is a real cost — on a host without * a vDSO fast path for CLOCK_PROCESS_CPUTIME_ID it runs to about a microsecond, @@ -80,16 +114,21 @@ inline double cpu_now() noexcept { return (double)std::clock() / (double)CLOCKS_ * so every clock() call in between is counted as part of the work. The spec asks * for a ~1 s CPU-time loop and a warmup; how often the clock is sampled inside * that loop is ours to choose. */ -constexpr double kBlockSeconds = 0.01; /* clock cost lands under ~0.01% of a block */ +inline double blockSeconds() noexcept +{ + const double s = loopSeconds() / 100.0; /* clock cost under ~0.01% of a block */ + return s < 0.01 ? s : 0.01; +} -/*! Grow a block of back-to-back operations until it spans ::kBlockSeconds. */ +/*! Grow a block of back-to-back operations until it spans ::blockSeconds. */ template inline unsigned long calibrateBlock(F &&body) { + const double target = blockSeconds(); for (unsigned long block = 1;; block *= 2) { const double t0 = cpu_now(); for (unsigned long k = 0; k < block; ++k) body(); - if (cpu_now() - t0 >= kBlockSeconds) return block; + if (cpu_now() - t0 >= target) return block; } } @@ -105,6 +144,7 @@ struct MeasureResult template inline MeasureResult measureLoop(F &&body, size_t bytes) { const unsigned long block = calibrateBlock(body); + const double budget = loopSeconds(); unsigned long it = 0; double el; @@ -114,7 +154,7 @@ template inline MeasureResult measureLoop(F &&body, size_t bytes) for (unsigned long k = 0; k < block; ++k) body(); it += block; el = cpu_now() - t0; - } while (el < 1.0); + } while (el < budget); const uint64_t c1 = cycles(); return MeasureResult{it, (double)(c1 - c0) / (double)it, el / (double)it * 1e9, diff --git a/bench/run_callgrind.sh b/bench/run_callgrind.sh index b25344b..d81b3f5 100755 --- a/bench/run_callgrind.sh +++ b/bench/run_callgrind.sh @@ -77,7 +77,7 @@ bytes_of() { grep -ohE 'BYTES=[0-9]+' "$OUT/$1.log" 2>/dev/null | head -1 | cut echo ">> Measuring instructions/op under Callgrind (this is slow) ..." >&2 echo echo "===============================================================================" -echo " SofaBuffers C++ instruction cost (Callgrind, Ir/op)" +echo " SofaBuffers pure-C++20 instruction cost (Callgrind, Ir/op)" echo " instructions/op: lower is better. Deterministic & machine-independent." echo "===============================================================================" printf "%-26s %16s %9s\n" "Workload" "instr/op" "bytes" diff --git a/bench/test_bench_tools.sh b/bench/test_bench_tools.sh index 0652dc4..1718066 100755 --- a/bench/test_bench_tools.sh +++ b/bench/test_bench_tools.sh @@ -1,24 +1,35 @@ #!/usr/bin/env bash # -# SofaBuffers pure-C++20 — guards the benchmark tooling's single sources of truth. +# SofaBuffers pure-C++20 — guards the benchmark tooling against BENCH_SPEC. # # CORELIB_PLAN §10 requires three benchmark tools (`bench`, `perf`, -# `run_callgrind.sh`) that follow one specification, so that their numbers stay -# comparable across languages. That only holds if the three share one definition -# of the workloads, one set of stream adapters and one timing harness; a copied -# definition lets two tools drift apart silently. This test checks the sharing -# structurally (no second copy in the tree) and behaviourally (the list the -# Callgrind driver consumes really is the list `bench` dispatches on, and a -# workload the binary rejects aborts the driver with a diagnostic instead of -# printing a dash). +# `run_callgrind.sh`) that follow one specification — BENCH_SPEC.md — so that +# their numbers stay comparable across languages. Two things have to hold for +# that, and neither is visible to a C++ unit test: # -# Usage: test_bench_tools.sh +# * **The workloads are BENCH_SPEC's**, all of them, with the cross-port parity +# sizes it fixes (the `blob 1MB` message is 1,000,005 bytes, `composite` is +# 956). A port that quietly ships a subset still prints a table that parses, +# and the missing rows only show up as a gap in the comparison. +# * **The output matches BENCH_SPEC's grammar**, since a row the central +# harness cannot parse is a row that does not exist. The regexes below are +# the ones from BENCH_SPEC "Output grammar", not a paraphrase. +# +# On top of that the three tools must share one definition of the workloads, the +# stream adapters and the timing harness; a copied definition lets two tools +# drift apart silently. That part is checked structurally (no second copy in the +# tree) and behaviourally (the list the Callgrind driver consumes really is the +# list `bench` dispatches on, and a workload the binary rejects aborts the driver +# with a diagnostic instead of printing a dash). +# +# Usage: test_bench_tools.sh [] # # SPDX-License-Identifier: MIT set -uo pipefail -BIN="${1:?usage: test_bench_tools.sh }" -SRC="${2:?usage: test_bench_tools.sh }" +BIN="${1:?usage: test_bench_tools.sh []}" +SRC="${2:?usage: test_bench_tools.sh []}" +PERF="${3:-}" # CTest maps 77 to "skipped" (SKIP_RETURN_CODE): a build that did not produce the # bench binary (test-only target selection) has nothing to check here. @@ -27,9 +38,19 @@ if [ ! -x "$BIN" ]; then exit 77 fi +# The measured loop is ~1 s of CPU time per workload by design (BENCH_SPEC +# "Timing"), which is a minute of CI for a grammar check. The tools honour +# SOFAB_BENCH_SECONDS so this test can drive the *same* code path over a token +# loop: what is being checked here is the shape of the table, never the numbers. +export SOFAB_BENCH_SECONDS=0.001 + fails=0 fail() { echo "FAIL: $*" >&2; fails=$((fails + 1)); } ok() { echo " ok: $*"; } +# A group of checks reports one line: "ok" only when nothing in it failed, so a +# passing summary can never sit under the failures it is summarising. +mark() { before="$fails"; } +done_ok() { [ "$fails" = "$before" ] && ok "$*"; } TMP="$(mktemp -d)" trap 'rm -rf "$TMP"' EXIT @@ -64,15 +85,77 @@ done # Every published name must actually run, and report its message size (the # Callgrind driver reads BYTES= out of the single-shot run's stderr). +declare -A bytes_of=() for w in "${names[@]}"; do if ! "$BIN" "$w" >"$TMP/$w.out" 2>"$TMP/$w.err"; then fail "single-shot run of published workload '$w' exited non-zero" continue fi - grep -qE 'BYTES=[0-9]+' "$TMP/$w.err" || fail "workload '$w' printed no BYTES= line" + b="$(grep -ohE 'BYTES=[0-9]+' "$TMP/$w.err" | head -1 | cut -d= -f2)" + [ -n "$b" ] || fail "workload '$w' printed no BYTES= line" + bytes_of["$w"]="$b" done ok "every published workload runs single-shot and reports BYTES=" +# --- 1b. the published set is BENCH_SPEC's, and only BENCH_SPEC's ---------- +# +# BENCH_SPEC fixes four datasets and eleven rows, of which exactly one — +# `encode: blob 1MB passthrough` — is optional (a port that does not implement +# CORELIB_PLAN §5.1 pass-through omits it rather than printing a placeholder). +# Anything outside that set would land in the cross-language comparison tables as +# a row no other port has. + +required_labels=( + "encode: u64 array (1000)" + "encode: typical message" + "encode: blob 1MB one-shot" + "encode: blob 1MB streaming" + "encode: composite" + "decode: u64 array (1000)" + "decode: typical message" + "decode: blob 1MB" + "decode: composite" + "decode: composite skip-all" +) + +# BENCH_SPEC "Output grammar", verbatim: the label alternatives the central +# harness matches. A label outside it is a row that will not be parsed. +SPEC_LABEL='(encode|decode): (u64 array \(1000\)|typical message|blob 1MB one-shot|blob 1MB streaming|blob 1MB passthrough|blob 1MB|composite skip-all|composite)' + +mark +for want in "${required_labels[@]}"; do + found=0 + for have in "${labels[@]}"; do [ "$have" = "$want" ] && found=1; done + [ "$found" = 1 ] || fail "BENCH_SPEC row '$want' is not published by 'bench --list'" +done +for have in "${labels[@]}"; do + grep -qE "^$SPEC_LABEL$" <<<"$have" \ + || fail "row label '$have' is not one BENCH_SPEC's output grammar admits" +done +done_ok "every BENCH_SPEC row is published, and no row outside its grammar is" + +# --- 1c. the cross-port parity sizes --------------------------------------- +# +# BENCH_SPEC states the encoded size of two of its messages outright and calls +# each "a parity check": a port whose figure differs has diverged on the wire, +# and its whole column is then measuring something else. `blob 1MB` is a 1-byte +# header plus a 4-byte fixlen word plus 1,000,000 payload bytes; `composite`'s +# 956 comes from the reference implementation (corelib-rs). + +parity_size() { # $1 workload substring, $2 expected size + for w in "${names[@]}"; do + case "$w" in + *"$1"*) + [ "${bytes_of[$w]:-}" = "$2" ] \ + || fail "workload '$w' reports ${bytes_of[$w]:-} bytes, BENCH_SPEC's parity size is $2";; + esac + done +} +mark +parity_size blob 1000005 +parity_size composite 956 +done_ok "the blob 1MB (1000005) and composite (956) parity sizes hold" + # An unpublished name must be rejected, not silently measured as something else. if "$BIN" no_such_workload >/dev/null 2>"$TMP/bogus.err"; then fail "an unknown workload name was accepted" @@ -100,7 +183,8 @@ ok "run_callgrind.sh and CMakeLists.txt hold no copy of the workload list" for f in bench.cpp perf.cpp; do grep -q '#include "bench_common.hpp"' "$SRC/$f" \ || fail "$f does not include the shared bench_common.hpp" - for sym in 'class OStreamRaw' 'class IStreamRaw' 'double cpu_now' 'kBlockSeconds ='; do + for sym in 'class OStreamRaw' 'class IStreamRaw' 'double cpu_now' \ + 'double loopSeconds' 'double blockSeconds'; do grep -q "$sym" "$SRC/$f" \ && fail "$f defines its own '$sym' — that belongs in bench_common.hpp" done @@ -160,6 +244,67 @@ else ok "run_callgrind.sh aborts with the captured diagnostic when a run fails" fi +# --- 5. the throughput table matches BENCH_SPEC's output grammar ----------- +# +# A row the central harness cannot parse is a row that does not exist, so this +# runs the real table (over a token loop, see SOFAB_BENCH_SECONDS above) and +# holds it against the spec's regexes rather than against a description of them. + +if "$BIN" >"$TMP/bench.out" 2>"$TMP/bench.err"; then + mark + grep -qE '^=== SofaBuffers .+ throughput \(CPU time, MB/s\) ===$' "$TMP/bench.out" \ + || fail "the throughput table has no '=== SofaBuffers