diff --git a/README.md b/README.md index 7f00a2a..a9e949e 100644 --- a/README.md +++ b/README.md @@ -673,7 +673,7 @@ Always give `--parallel` an explicit job count. Bare `--parallel` defers to the native build tool's default, and with the Unix Makefiles generator that is `make -j` with *no* limit — one compiler per translation unit, all at once. -Two suites run under CTest: +Three suites run under CTest: - **`test_roundtrip`** — encode/decode/nested/chunked/skip checks plus the three-valued decode outcome (§7: COMPLETE / INCOMPLETE / INVALID), malformed-input @@ -703,6 +703,15 @@ Two 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 + 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. ### Coverage and API docs @@ -739,11 +748,27 @@ hosts and against the other language ports: ```sh bash bench/run_callgrind.sh # Ir/op table (needs valgrind) -cmake --build build --target run_bench_callgrind # same runs via CMake, raw callgrind.*.out files +cmake --build build --target run_bench_callgrind # the same script, driven from CMake ``` Those figures are the head-to-head data below. +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 +tool and go stale in another. The stream adapters and the timing rules +(BENCH_SPEC's ~1 s CPU-time loop) likewise live once, in `bench/bench_common.hpp`, +included by both `bench` and `perf`. `bench ` runs a single operation +and exits — the Callgrind single-shot mode; an unknown name is rejected, and a +run that yields no figure aborts the table instead of printing a `-`: + +```sh +build/bench/bench --list # the workloads, one "namelabel" per line +build/bench/bench encode_typical # one operation, then exit (Callgrind mode) +``` + +`ctest -R test_bench_tools` guards that sharing. + ## Choosing between the two C++ corelibs SofaBuffers ships **two** C++ implementations of the same wire format, tuned for diff --git a/bench/CMakeLists.txt b/bench/CMakeLists.txt index aef59d3..d76c2b8 100644 --- a/bench/CMakeLists.txt +++ b/bench/CMakeLists.txt @@ -15,18 +15,25 @@ add_custom_target(run_perf COMMAND perf DEPENDS perf USES_TERMINAL) # Machine-independent instruction counts: run each bench workload once under # Callgrind, collecting only the run_ entry point (extern "C" + noinline # in bench.cpp), so the figures line up with the C / C++ corelib benchmarks. +# +# The target drives bench/run_callgrind.sh instead of looping over its own copy of +# the workload names: the list lives once, in the table bench.cpp dispatches on, +# and reaches every tool through `bench --list` (CORELIB_PLAN §10). find_program(VALGRIND_EXECUTABLE valgrind) if(VALGRIND_EXECUTABLE) add_custom_target(run_bench_callgrind - COMMAND ${CMAKE_COMMAND} -E echo "Counting instructions/op with Callgrind" - DEPENDS bench - USES_TERMINAL) - foreach(workload encode_u64_array encode_typical decode_u64_array decode_typical) - add_custom_command(TARGET run_bench_callgrind POST_BUILD - COMMAND ${VALGRIND_EXECUTABLE} --tool=callgrind --quiet - --callgrind-out-file=${CMAKE_BINARY_DIR}/callgrind.${workload}.out - --collect-atstart=no --toggle-collect=run_${workload} - $ ${workload} - VERBATIM) - endforeach() + COMMAND ${CMAKE_COMMAND} -E env BUILD=${CMAKE_BINARY_DIR} + bash ${CMAKE_CURRENT_SOURCE_DIR}/run_callgrind.sh + USES_TERMINAL + VERBATIM) + 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). +add_test(NAME test_bench_tools + COMMAND bash ${CMAKE_CURRENT_SOURCE_DIR}/test_bench_tools.sh + $ ${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 7d77b73..8db3cc9 100644 --- a/bench/bench.cpp +++ b/bench/bench.cpp @@ -18,12 +18,11 @@ * SPDX-License-Identifier: MIT */ -#include "sofab/sofab.hpp" +#include "bench_common.hpp" #include #include #include -#include #include #include @@ -32,18 +31,8 @@ namespace { -/* Streams that drive a caller-owned raw buffer (no heap in the measured run). */ -class OStreamRaw : public sofab::OStreamImpl -{ -public: - void init(uint8_t *b, size_t n) noexcept { initBuffer(b, n, 0); } -}; - -class IStreamRaw : public sofab::IStreamImpl -{ -public: - template void init(F &&cb) noexcept { topCallback_ = std::forward(cb); } -}; +using sofab_bench::IStreamRaw; +using sofab_bench::OStreamRaw; /* shared buffers */ uint64_t src[N]; @@ -92,40 +81,10 @@ void encode_typical(OStreamRaw &os) os.sequenceEnd(); } -double cpu_now() { return (double)std::clock() / (double)CLOCKS_PER_SEC; } - -/* 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, - * which is more than an entire `typical message` operation — so reading it once - * per iteration, as this loop used to, measures mostly the clock. 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 */ - -long calibrateBlock(void (*fn)()) -{ - for (long block = 1;; block *= 2) - { - double t0 = cpu_now(); - for (long k = 0; k < block; ++k) fn(); - if (cpu_now() - t0 >= kBlockSeconds) return block; - } -} - double measure(void (*fn)(), size_t bytes) { fn(); /* warmup */ - const long block = calibrateBlock(fn); - double t0 = cpu_now(); - long it = 0; - double el; - do { - for (long k = 0; k < block; ++k) fn(); - it += block; - el = cpu_now() - t0; - } while (el < 1.0); - return (double)bytes * (double)it / el / 1e6; /* MB/s, MB = 1e6 bytes */ + return sofab_bench::measureLoop([fn] { fn(); }, bytes).mb_s; } } // namespace @@ -176,52 +135,90 @@ extern "C" __attribute__((noinline)) void run_decode_typical() is.feed(typ_buf, typ_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 + * array, so a workload cannot exist in one of them and be missing from another. + * `bench --list` prints it as "namelabel" lines; run_callgrind.sh and the + * run_bench_callgrind CMake target take their workload names and their row + * labels from that output instead of keeping copies (CORELIB_PLAN §10). */ + +namespace +{ + +struct Workload +{ + const char *name; /* CLI name; the Callgrind toggle is run_ */ + const char *label; /* row label, per BENCH_SPEC's output grammar */ + void (*setup)(); /* prepares the input, excluded from collection */ + void (*run)(); /* the measured operation */ + const size_t *bytes; /* message size, valid once setup+run have run */ +}; + +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}, + {"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}, +}; + +const Workload *find(const char *name) +{ + for (const Workload &w : kWorkloads) + if (!strcmp(w.name, name)) return &w; + return nullptr; +} + /* ---- single-shot mode (one operation, for Callgrind instruction counts) -- */ -static int run_one(const char *w) +int run_one(const char *name) { - make_src(); - if (!strcmp(w, "encode_u64_array")) { - run_encode_u64_array(); - } else if (!strcmp(w, "encode_typical")) { - run_encode_typical(); - } else if (!strcmp(w, "decode_u64_array")) { - run_encode_u64_array(); /* setup (excluded from collection) */ - run_decode_u64_array(); - } else if (!strcmp(w, "decode_typical")) { - run_encode_typical(); /* setup (excluded from collection) */ - run_decode_typical(); - } else { - fprintf(stderr, "unknown workload: %s\n", w); + const Workload *w = find(name); + if (!w) + { + fprintf(stderr, "unknown workload: %s\n", name); return 1; } - size_t bytes = (!strcmp(w, "encode_u64_array") || !strcmp(w, "decode_u64_array")) - ? enc_u64_used : typ_used; + make_src(); + 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(), bytes); + (unsigned long long)dec_array[0], T.f1, T.s_f2, T.f5.c_str(), *w->bytes); return 0; } +} // namespace + int main(int argc, char **argv) { T.f5.reserve(16); /* string read buffer, reserved outside the measured run */ if (argc >= 2) + { + if (!strcmp(argv[1], "--list")) + { + for (const Workload &w : kWorkloads) printf("%s\t%s\n", w.name, w.label); + return 0; + } return run_one(argv[1]); + } make_src(); - run_encode_u64_array(); - run_encode_typical(); - size_t ba = enc_u64_used, bt = typ_used; + for (const Workload &w : kWorkloads) /* prime every buffer and message size */ + { + if (w.setup) w.setup(); + w.run(); + } printf("=== SofaBuffers pure-C++20 throughput (CPU time, MB/s) ===\n"); printf("%-26s %12s\n", "Workload", "MB/s"); printf("%-26s %12s\n", "--------", "----"); - printf("%-26s %12.2f\n", "encode: u64 array (1000)", measure(run_encode_u64_array, ba)); - printf("%-26s %12.2f\n", "encode: typical message", measure(run_encode_typical, bt)); - printf("%-26s %12.2f\n", "decode: u64 array (1000)", measure(run_decode_u64_array, ba)); - printf("%-26s %12.2f\n", "decode: typical message", measure(run_decode_typical, bt)); + 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"); return 0; } diff --git a/bench/bench_common.hpp b/bench/bench_common.hpp new file mode 100644 index 0000000..52f5c18 --- /dev/null +++ b/bench/bench_common.hpp @@ -0,0 +1,126 @@ +/*! + * @file bench_common.hpp + * @brief Shared plumbing for the SofaBuffers pure-C++20 benchmark tools. + * + * CORELIB_PLAN §10 asks for three benchmark tools (`bench`, `perf`, + * `run_callgrind.sh`) that follow one specification — BENCH_SPEC.md — so their + * numbers stay comparable across languages. That only holds while they share one + * definition of the pieces the spec constrains, so both harnesses take their + * stream adapters and their timing rules from here rather than keeping a private + * copy that can drift. + * + * SPDX-License-Identifier: MIT + */ +#ifndef SOFAB_BENCH_COMMON_HPP +#define SOFAB_BENCH_COMMON_HPP + +#include "sofab/sofab.hpp" + +#include +#include +#include +#include + +#if defined(__x86_64__) || defined(__i386__) +#include +#define PERF_HAVE_CYCLES 1 +#elif defined(__aarch64__) +#define PERF_HAVE_CYCLES 1 +#else +#define PERF_HAVE_CYCLES 0 +#endif + +namespace sofab_bench +{ + +/* ---- stream adapters ------------------------------------------------------ + * + * The benchmarks' only view of the corelib's public surface: streams over a + * caller-owned raw buffer, so no heap traffic lands in the measured run. One + * definition, so a change to that surface cannot leave one tool building and the + * other not. */ + +class OStreamRaw : public sofab::OStreamImpl +{ +public: + void init(uint8_t *b, size_t n) noexcept { initBuffer(b, n, 0); } +}; + +class IStreamRaw : public sofab::IStreamImpl +{ +public: + template void init(F &&cb) noexcept { topCallback_ = std::forward(cb); } +}; + +/* ---- timing harness ------------------------------------------------------- */ + +/*! Hardware cycle counter (x86 TSC / AArch64 virtual count); 0 where absent. */ +inline uint64_t cycles() noexcept +{ +#if defined(__x86_64__) || defined(__i386__) + return (uint64_t)__rdtsc(); +#elif defined(__aarch64__) + uint64_t v; + __asm__ volatile("mrs %0, cntvct_el0" : "=r"(v)); + return v; +#else + return 0; +#endif +} + +/*! Process CPU time in seconds (not wall-clock). */ +inline double cpu_now() noexcept { return (double)std::clock() / (double)CLOCKS_PER_SEC; } + +/* 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, + * which is more than an entire `typical message` operation — so reading it once + * per iteration, as these loops used to, measures mostly the clock. It corrupts + * cycles/op too, not just the timing: the cycle counter brackets the whole loop, + * 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 */ + +/*! Grow a block of back-to-back operations until it spans ::kBlockSeconds. */ +template inline unsigned long calibrateBlock(F &&body) +{ + 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; + } +} + +struct MeasureResult +{ + unsigned long iters; + double cycles_op; + double ns_op; + double mb_s; /*!< MB = 1e6 bytes, per BENCH_SPEC. */ +}; + +/*! BENCH_SPEC's measured loop: ~1 s of CPU time, clock sampled once per block. */ +template inline MeasureResult measureLoop(F &&body, size_t bytes) +{ + const unsigned long block = calibrateBlock(body); + + unsigned long it = 0; + double el; + const uint64_t c0 = cycles(); + const double t0 = cpu_now(); + do { + for (unsigned long k = 0; k < block; ++k) body(); + it += block; + el = cpu_now() - t0; + } while (el < 1.0); + const uint64_t c1 = cycles(); + + return MeasureResult{it, (double)(c1 - c0) / (double)it, el / (double)it * 1e9, + (double)bytes * (double)it / el / 1e6}; +} + +} // namespace sofab_bench + +#endif /* SOFAB_BENCH_COMMON_HPP */ diff --git a/bench/perf.cpp b/bench/perf.cpp index e64cad3..700ab4d 100644 --- a/bench/perf.cpp +++ b/bench/perf.cpp @@ -13,47 +13,26 @@ * SPDX-License-Identifier: MIT */ -#include "sofab/sofab.hpp" +#include "bench_common.hpp" #include #include #include -#include #include #include -#if defined(__x86_64__) || defined(__i386__) -#include -#define PERF_HAVE_CYCLES 1 -static inline uint64_t perf_cycles() { return (uint64_t)__rdtsc(); } -#elif defined(__aarch64__) -#define PERF_HAVE_CYCLES 1 -static inline uint64_t perf_cycles() { uint64_t v; __asm__ volatile("mrs %0, cntvct_el0" : "=r"(v)); return v; } -#else -#define PERF_HAVE_CYCLES 0 -static inline uint64_t perf_cycles() { return 0; } -#endif - namespace { +using sofab_bench::IStreamRaw; +using sofab_bench::OStreamRaw; + #define PERF_STRING "perf-benchmark-message" const uint32_t perf_samples[8] = {1000000u, 2000000u, 3000000u, 4000000u, 5000000u, 6000000u, 7000000u, 8000000u}; const int32_t perf_deltas[8] = {-100000, -200000, -300000, -400000, -500000, -600000, -700000, -800000}; const double perf_fp64[4] = {3.14159265, 6.28318530, 9.42477795, 12.56637060}; -class OStreamRaw : public sofab::OStreamImpl -{ -public: - void init(uint8_t *b, size_t n) noexcept { initBuffer(b, n, 0); } -}; -class IStreamRaw : public sofab::IStreamImpl -{ -public: - template void init(F &&cb) noexcept { topCallback_ = std::forward(cb); } -}; - size_t perf_encode(uint8_t *buf, size_t buflen) { OStreamRaw os; @@ -119,9 +98,9 @@ void perf_decode(const uint8_t *buf, size_t len, PerfOut &out) is.feed(buf, len); } -struct PerfResult { unsigned long iters; double cycles_op; double ns_op; double mb_s; }; - -double cpu_now() { return (double)std::clock() / (double)CLOCKS_PER_SEC; } +/*! The measured-loop result and the ~1 s CPU-time loop itself come from + * bench_common.hpp, so `perf` and `bench` cannot time differently. */ +using PerfResult = sofab_bench::MeasureResult; void perf_report(const char *what, PerfResult r, size_t bytes) { @@ -138,40 +117,6 @@ void perf_report(const char *what, PerfResult r, size_t bytes) printf(" throughput : %.1f MB/s (speedtest, MB = 1e6 bytes)\n", r.mb_s); } -/* Sample the CPU clock once per block of operations rather than once per - * operation. std::clock() can cost around a microsecond — comparable to, or - * larger than, one operation on this message — so a per-iteration reading lands - * squarely inside the measurement. It corrupts cycles/op too, not just the - * timing: the cycle counter brackets the whole loop, so every clock() call in - * between is counted as part of the work. The block is grown until it spans - * long enough that a single reading cannot matter. */ -constexpr double kBlockSeconds = 0.01; /* clock cost lands under ~0.01% of a block */ - -template -PerfResult measure_loop(F &&body, size_t bytes) -{ - unsigned long block = 1; - for (;; block *= 2) - { - double t0 = cpu_now(); - for (unsigned long k = 0; k < block; ++k) body(); - if (cpu_now() - t0 >= kBlockSeconds) break; - } - - unsigned long it = 0; - double el; - uint64_t c0 = perf_cycles(); - double t0 = cpu_now(); - do { - for (unsigned long k = 0; k < block; ++k) body(); - it += block; - el = cpu_now() - t0; - } while (el < 1.0); - uint64_t c1 = perf_cycles(); - return PerfResult{it, (double)(c1 - c0) / (double)it, el / (double)it * 1e9, - (double)bytes * (double)it / el / 1e6}; -} - PerfResult measure_encode(uint8_t *buf, size_t buflen, size_t &msg_size) { volatile size_t sink = 0; @@ -179,7 +124,7 @@ PerfResult measure_encode(uint8_t *buf, size_t buflen, size_t &msg_size) for (unsigned i = 0; i < 1000u; i++) msg = perf_encode(buf, buflen); /* warmup */ msg_size = msg; - PerfResult r = measure_loop([&] { sink += perf_encode(buf, buflen); }, msg); + PerfResult r = sofab_bench::measureLoop([&] { sink += perf_encode(buf, buflen); }, msg); (void)sink; return r; } @@ -189,7 +134,7 @@ PerfResult measure_decode(const uint8_t *buf, size_t len, PerfOut &out) volatile uint32_t sink = 0; for (unsigned i = 0; i < 1000u; i++) perf_decode(buf, len, out); /* warmup */ - PerfResult r = measure_loop([&] { perf_decode(buf, len, out); sink += out.u32; }, len); + PerfResult r = sofab_bench::measureLoop([&] { perf_decode(buf, len, out); sink += out.u32; }, len); (void)sink; return r; } diff --git a/bench/run_callgrind.sh b/bench/run_callgrind.sh index d75d270..b25344b 100755 --- a/bench/run_callgrind.sh +++ b/bench/run_callgrind.sh @@ -38,26 +38,42 @@ fi OUT="$(mktemp -d)" trap 'rm -rf "$OUT"' EXIT -WORKLOADS=(encode_u64_array encode_typical decode_u64_array decode_typical) + +# The workloads and their row labels come from the bench binary itself +# ("namelabel" per line, straight out of the table bench.cpp dispatches on). +# CORELIB_PLAN §10 wants the three tools to follow one definition, so this script +# keeps no list of its own: a workload added, removed or renamed in bench.cpp +# shows up here without an edit, and can never silently disagree. +if ! LIST="$("$BIN" --list 2>"$OUT/list.log")"; then + echo "error: '$BIN --list' failed — rebuild the bench binary:" >&2 + cat "$OUT/list.log" >&2 + exit 1 +fi + +WORKLOADS=(); LABELS=() +while IFS=$'\t' read -r name label; do + [ -n "${name:-}" ] || continue + WORKLOADS+=("$name"); LABELS+=("${label:-$name}") +done <<<"$LIST" + +if [ "${#WORKLOADS[@]}" -eq 0 ]; then + echo "error: '$BIN --list' published no workloads." >&2 + exit 1 +fi run_cg() { # $1 workload - valgrind --tool=callgrind --collect-atstart=no --toggle-collect="run_$1" \ + if ! valgrind --tool=callgrind --collect-atstart=no --toggle-collect="run_$1" \ --callgrind-out-file="$OUT/$1.out" "$BIN" "$1" \ - >/dev/null 2>"$OUT/$1.log" + >/dev/null 2>"$OUT/$1.log"; then + echo "error: the Callgrind run for workload '$1' failed:" >&2 + cat "$OUT/$1.log" >&2 + exit 1 + fi } ir_of() { grep -m1 '^summary:' "$OUT/$1.out" 2>/dev/null | awk '{print $2}'; } bytes_of() { grep -ohE 'BYTES=[0-9]+' "$OUT/$1.log" 2>/dev/null | head -1 | cut -d= -f2; } -label() { - case "$1" in - encode_u64_array) echo "encode: u64 array (1000)";; - encode_typical) echo "encode: typical message";; - decode_u64_array) echo "decode: u64 array (1000)";; - decode_typical) echo "decode: typical message";; - esac -} - echo ">> Measuring instructions/op under Callgrind (this is slow) ..." >&2 echo echo "===============================================================================" @@ -67,10 +83,18 @@ echo "========================================================================== printf "%-26s %16s %9s\n" "Workload" "instr/op" "bytes" printf "%-26s %16s %9s\n" "--------" "--------" "-----" -for w in "${WORKLOADS[@]}"; do +for i in "${!WORKLOADS[@]}"; do + w="${WORKLOADS[$i]}" run_cg "$w" - ir="$(ir_of "$w")"; b="$(bytes_of "$w")" - printf "%-26s %16s %9s\n" "$(label "$w")" "${ir:--}" "${b:--}" + # A missing figure is a failure, not a dash: a table with a "-" in it looks + # exactly like a fresh one, so a broken measurement has to stop the run. + ir="$(ir_of "$w" || true)"; b="$(bytes_of "$w" || true)" + if [ -z "$ir" ] || [ -z "$b" ]; then + echo "error: workload '$w' produced no instruction count / message size:" >&2 + cat "$OUT/$w.log" >&2 + exit 1 + fi + printf "%-26s %16s %9s\n" "${LABELS[$i]}" "$ir" "$b" done echo echo "Ir = instructions retired (Callgrind). Independent of CPU clock and OS" diff --git a/bench/test_bench_tools.sh b/bench/test_bench_tools.sh new file mode 100755 index 0000000..0652dc4 --- /dev/null +++ b/bench/test_bench_tools.sh @@ -0,0 +1,167 @@ +#!/usr/bin/env bash +# +# SofaBuffers pure-C++20 — guards the benchmark tooling's single sources of truth. +# +# 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). +# +# 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 }" + +# 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. +if [ ! -x "$BIN" ]; then + echo "SKIP: bench binary not built at $BIN" + exit 77 +fi + +fails=0 +fail() { echo "FAIL: $*" >&2; fails=$((fails + 1)); } +ok() { echo " ok: $*"; } + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +# --- 1. `bench --list` is the published workload table --------------------- + +if ! "$BIN" --list >"$TMP/list.txt" 2>"$TMP/list.err"; then + fail "'$BIN --list' exited non-zero: $(cat "$TMP/list.err")" + echo "$fails failure(s)" >&2 + exit 1 +fi + +names=(); labels=() +while IFS=$'\t' read -r name label; do + [ -n "${name:-}" ] || continue + names+=("$name"); labels+=("${label:-}") +done <"$TMP/list.txt" + +if [ "${#names[@]}" -eq 0 ]; then + fail "'bench --list' printed no workloads" + echo "$fails failure(s)" >&2 + exit 1 +fi +ok "bench --list published ${#names[@]} workloads" + +for i in "${!names[@]}"; do + case "${names[$i]}" in + *[!a-z0-9_]*|"") fail "workload name '${names[$i]}' is not a Callgrind-safe symbol suffix";; + esac + [ -n "${labels[$i]}" ] || fail "workload '${names[$i]}' has no row label" +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). +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" +done +ok "every published workload runs single-shot and reports BYTES=" + +# 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" +else + grep -q 'unknown workload' "$TMP/bogus.err" || fail "unknown workload rejected without a diagnostic" +fi +ok "an unknown workload name is rejected with a diagnostic" + +# --- 2. no second copy of the workload list -------------------------------- + +for f in run_callgrind.sh CMakeLists.txt; do + for i in "${!names[@]}"; do + if grep -qF -- "${names[$i]}" "$SRC/$f"; then + fail "$f hardcodes the workload name '${names[$i]}' — it must come from 'bench --list'" + fi + if grep -qF -- "${labels[$i]}" "$SRC/$f"; then + fail "$f hardcodes the row label '${labels[$i]}' — it must come from 'bench --list'" + fi + done +done +ok "run_callgrind.sh and CMakeLists.txt hold no copy of the workload list" + +# --- 3. no second copy of the adapters and the timing harness -------------- + +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 + grep -q "$sym" "$SRC/$f" \ + && fail "$f defines its own '$sym' — that belongs in bench_common.hpp" + done +done +ok "bench.cpp and perf.cpp share the adapters and the timing harness" + +# --- 4. the Callgrind driver fails loudly on a rejected run ---------------- +# +# Driven with a stub `valgrind` so this needs no real Valgrind (and takes +# milliseconds). The stub is passed the same argv the driver builds, so it also +# proves the driver still invokes the binary with the published names. + +mkdir -p "$TMP/stub" "$TMP/fakebuild/bench" +ln -sf "$(cd "$(dirname "$BIN")" && pwd)/$(basename "$BIN")" "$TMP/fakebuild/bench/bench" + +cat >"$TMP/stub/valgrind" <<'STUB' +#!/usr/bin/env bash +out=""; argv=() +for a in "$@"; do + case "$a" in + --callgrind-out-file=*) out="${a#*=}";; + --*) ;; + *) argv+=("$a");; + esac +done +[ -n "$out" ] && printf 'summary: 4242\n' >"$out" +exec "${argv[@]}" +STUB +chmod +x "$TMP/stub/valgrind" + +if PATH="$TMP/stub:$PATH" BUILD="$TMP/fakebuild" bash "$SRC/run_callgrind.sh" \ + >"$TMP/cg.out" 2>"$TMP/cg.err"; then + for i in "${!names[@]}"; do + grep -qF -- "${labels[$i]}" "$TMP/cg.out" \ + || fail "run_callgrind.sh printed no row for '${names[$i]}'" + done + grep -q '4242' "$TMP/cg.out" || fail "run_callgrind.sh printed no instruction count" + ok "run_callgrind.sh prints one row per published workload" +else + fail "run_callgrind.sh failed on a successful run: $(cat "$TMP/cg.err")" +fi + +cat >"$TMP/stub/valgrind" <<'STUB' +#!/usr/bin/env bash +echo "stub-valgrind: simulated rejected run" >&2 +exit 1 +STUB +chmod +x "$TMP/stub/valgrind" + +if PATH="$TMP/stub:$PATH" BUILD="$TMP/fakebuild" bash "$SRC/run_callgrind.sh" \ + >"$TMP/cgf.out" 2>"$TMP/cgf.err"; then + fail "run_callgrind.sh exited 0 although the measured run failed" +else + grep -q 'simulated rejected run' "$TMP/cgf.err" \ + || fail "run_callgrind.sh swallowed the failing run's diagnostic" + grep -qE '^-+ +-+' "$TMP/cgf.out" >/dev/null 2>&1 # header only, no data rows + ok "run_callgrind.sh aborts with the captured diagnostic when a run fails" +fi + +if [ "$fails" -ne 0 ]; then + echo "$fails failure(s)" >&2 + exit 1 +fi +echo "bench tooling: all checks passed"