Cosa fa
- Macro per misura, confronto, fixture, byte ed elementi
- Segnala i cicli eliminati dall'ottimizzazione del compilatore
- Rileva le variazioni di frequenza
- Contatori hardware su Linux
- Controllo delle regressioni con confidenza al 99%
- Output JSON, CSV, tabella e HTML
Misurato
- i7-6700, GCC 15.2 su WSL2 / MSVC 19.51. Overhead dell'infrastruttura per iterazione: 0.28 ns e 0.61 ns (obiettivo 1 ns)
- Controllo: 0 falsi fallimenti su 100 e 98 regressioni del 10% rilevate su 100, secondo il modello di rumore
- Ripetibilità su 10 esecuzioni: da 0.4% a 14.1% e da 1.3% a 14.1%. Obiettivo del 2% non raggiunto su questa macchina
Limiti noti
- I contatori hardware non sono implementati su Windows (richiedono diritti di amministratore o un driver)
Ethereal::Bench · Tier 0, prerequisite
Measures without lying: batch calibration, warmup until stable, median/p90/p99/min/MAD (the mean is not computed), complete environment with a fingerprint, clock drift, hardware counters where they exist, a statistical regression gate, and JSON/CSV/table/HTML. C++17, depends only on Testing (it shares the runner: child processes, files, JSON/HTML escaping, glob, number generator). It does not link Ethereal.
---
Usage
#include <ethereal/cpp/bench/bench.hpp>
ETL_BENCH( TimeSuite, NowMonotonic )
{
for( auto _ : ETL_BENCH_LOOP )
ETL_DO_NOT_OPTIMIZE( Time::NowMonotonic() );
}
ETL_BENCH_ARGS( EncodingSuite, Base64Encode, std::size_t uSize )
{
const auto In = MakeInput( uSize ); // setup: runs once
std::vector< char > Out( Encoding::Base64EncodedSize( uSize ) );
std::size_t w = 0;
for( auto _ : ETL_BENCH_LOOP )
{
static_cast< void >( Encoding::Base64Encode( In, Out, w ) );
ETL_DO_NOT_OPTIMIZE( w );
}
ETL_BENCH_BYTES( uSize ); // throughput, in addition to latency
}
ETL_BENCH_RANGE( EncodingSuite, Base64Encode, 16, 64, 1024, 65536, 1048576 );
ETL_BENCH_CASE_FN( Scalar ) { ... }
ETL_BENCH_CASE_FN( Avx2 ) { if( !HasAvx2() ) ETL_BENCH_SKIP( "no AVX2" ); ... }
ETL_BENCH_COMPARE( EncodingSuite, Hex,
ETL_BENCH_CASE( "scalar", Scalar ), // the first one is the baseline for the ratios
ETL_BENCH_CASE( "avx2", Avx2 ) );Also: ETL_BENCH_F( CFixture, Name ) (SetUp/TearDown once, outside the timing), ETL_BENCH_ITEMS( n ), ETL_BENCH_PAUSE / ETL_BENCH_RESUME (each pair costs two clock reads: they are for setup, never for 1 ns of work), ETL_BENCH_COUNTER( "name", value ), ETL_BENCH_OPAQUE( x ), ETL_CLOBBER_MEMORY().
include( EtherealBench ) # cmake/EtherealBench.cmake
add_executable( my-benchmarks benchmarks.cpp )
etl_bench_target( my-benchmarks ) # links Bench + BenchMain and declares the real flagsThe three rules the compiler imposes
- **The result goes through
ETL_DO_NOT_OPTIMIZE**, otherwise the compiler deletes the work. Without a visible effect, the entire loop disappears, and the instrument reports it:LOOP ELIMINATED BY THE COMPILER. - So does the input. A constant or invariant input is computed once outside the loop (or at compile time): a non-const lvalue passed through
ETL_DO_NOT_OPTIMIZEis laundered (the compiler no longer knows its value), or pass the input throughETL_BENCH_OPAQUE. A body that costs the same as the minimal loop is flagged as suspect. - **
ETL_CLOBBER_MEMORYonly guarantees writes to memory that has escaped.** A local buffer whose address never left the function can have its writes deleted even with the barrier (measured: 64 writes in 1.4 ns). Pass the pointer throughETL_DO_NOT_OPTIMIZEbefore the loop.
Command line
Every benchmark executable is also the tool (etl-bench is the same main without benchmarks):
bench-core # table in the terminal
bench-core --repetitions 5 --out r.json # 5 separate processes, the canonical JSON
bench-core --filter 'Encoding.*:-*/avx2' --list
etl-bench --compare base.json r.json --threshold 5% --confidence 99 --commit-url 'https://.../compare/{old}...{new}'
etl-bench --update-baseline r.json --baseline-dir bench/baselines
etl-bench --html page.html r1.json r2.json --source-url https://.../blob/main --source-root C:/src --source-root /mnt/c/src
etl-bench --csv table.csv r.jsonExit code: 0 fine. 1 regression, missing benchmark or benchmark with an error. 2 usage. 3 refused (different environments, baseline with fewer than 3 repetitions, baseline measured with drift).
The text the instrument prints (table, gate, help, HTML) has been in English since 2026-10-05: REGRESSION, REFUSED, MISSING, equal, improved, SKIPPED, SUSPECT. The JSON keys did not change. The fingerprint keys moved to English on 2026-10-12 (nucleos_logicos → logical_cores, governador → governor, fixado → pinned, with yes/no instead of sim/nao...), and they change the fingerprint in the same way. The environment values that go into the fingerprint changed their text (turbo ligado (...) became on (...), otimizado sim (__OPTIMIZE__) became yes (__OPTIMIZE__), the desconhecido (...) values became unknown (...)): a baseline recorded before that date has a different fingerprint and is refused. Record the baseline again.
---
How it measures
| Phase | What it does |
|---|---|
| calibrate | the batch grows until it fills the window (2 ms). 1 ns is measured in batches of millions, 1 s one at a time. A batch of 2³² iterations that does not reach the window is a deleted loop: it is reported and gets no measurement |
| warm up | until three consecutive batches agree within 2% (or half a second). The batches are counted and discarded |
| measure | one sample per batch, until the minimum time and the minimum sample count (5 when a single operation already exceeds the window) |
The clock is only read at batch boundaries. Hardware counters are read outside the measured interval. The loop costs one cycle: the function that closes the batch returns the size of the next one instead of receiving it by reference. By reference, the counter's address escaped and the ETL_DO_NOT_OPTIMIZE barrier forced it to be stored and reread on every iteration (measured: 1.38 versus 0.28 ns).
**ETL_DO_NOT_OPTIMIZE on MSVC does not use the classic opaque call.** That form (passing the address to a noinline function in the same unit) failed the test: MSVC /O1 and /O2 sees that the function does nothing and hoisted 64 dependent multiplications out of the loop. It gave 0.7 ns per iteration, which is impossible. Scalars use a volatile (also immune to /GL). Everything else uses a library function in another translation unit that stores the pointer in a volatile. **With /GL (LTCG), the non-scalar path loses the opacity of the separate unit.** The volatile that stores the pointer keeps the object alive, but that was not measured under /GL.
---
The gate
etl-bench --compare compares entire distributions, instead of two medians: hierarchical resampling of the repetitions (separate processes) and, within each one, of the samples. The variation between runs thus goes into the uncertainty. It fails when there is 99% confidence that the median got worse by more than the threshold. A benchmark that disappeared fails (a missing benchmark is indistinguishable from one that never fails). Environments with different fingerprints are refused, with the fields that differ. The baseline is only recorded with ≥ 3 repetitions and no drift, and it never changes on its own.
---
Measurements
Test machine: i7-6700 (4 cores / 8 logical), Windows 10 with the "Balanced" plan. GCC 15.2 on WSL2, MSVC 19.51 native. The tests that produce them are in tests/bench_*. The repeatability and gate power measurements are in tools/bench_check/.
The instrument's cost (a loop with one ETL_DO_NOT_OPTIMIZE, the spec asks for < 1 ns): GCC 0.28 ns, MSVC 0.61 ns per iteration.
**ETL_DO_NOT_OPTIMIZE at each level** (bench.dno.*): 64 dependent xorshift steps cannot fit in less than 10.7 ns, not even at 6 GHz. If the barrier failed, the measurement would give ~0.3 ns: impossible.
| level | laundered scalar | const scalar | struct | writes + clobber | the same without barriers (the control) |
|---|---|---|---|---|---|
| GCC -O0 | 491 ns | 491 ns | 495 ns | 146 ns | not applicable (nothing is deleted at -O0) |
| GCC -O1 | 97 ns | 101 ns | 121 ns | 24 ns | not applicable (GCC -O1 does not delete dead code in loops: 18.8 ns) |
| GCC -O2 | 98 ns | 98 ns | 116 ns | 22 ns | loop eliminated |
| GCC -O3 | 102 ns | 99 ns | 124 ns | 24 ns | loop eliminated |
| GCC -Os | 98 ns | 99 ns | 118 ns | 38 ns | 0.58 ns |
| MSVC /Od | 489 ns | 484 ns | 528 ns | 129 ns | not applicable |
| MSVC /O1 | 99 ns | 98 ns | 116 ns | 22 ns | loop eliminated |
| MSVC /O2 | 98 ns | 96 ns | 116 ns | 20 ns | loop eliminated |
| MSVC /Ox | 97 ns | 96 ns | 118 ns | 21 ns | loop eliminated |
The control is what gives the table its value: at the levels where the compiler deletes work, it deleted it without the barriers and kept it with them.
Calibration from ~1 ns to ~1 s (bench.measurements, against a reference measured without the instrument):
| work | GCC | MSVC |
|---|---|---|
| ~1.7 ns (1 step) | −8.3% | +0.4% |
| ~1 µs | +5.0% | −2.8% |
| ~1 ms | +1.5% | −2.2% |
| ~1 s (batch of 1, 5 samples) | +4.9% | −0.4% |
Planted foldable input (bench.measurements): three splitmix64 finalizers over a constant. GCC 0.28 ns and MSVC 1.0 ns, the same as the empty loop: reported. The same with the input laundered: 3.1 ns (GCC) and 4.1 ns (MSVC), not reported. A first version of the test planted a 64-step chain with a constant input, and GCC does not fold it (102 ns, equal to the laundered one). That is why the plant is now straight-line code, which any optimizer folds.
Hardware counters: on this machine's WSL2, available and real (64 steps = 712 instructions, 350 cycles, IPC 2.04 per iteration). On Windows, unavailable with the reason, and the measurement runs anyway. The processor counters on Windows can only be read through ETW with administrator privilege (or through a driver): this machine runs without it (checked), and a path that cannot be tested here was not included. QueryThreadCycleTime, which does not require privilege, counts reference cycles (the TSC) instead of core cycles: publishing it as "cycles" would give wrong IPC values, and that was not done.
Clock drift: it really triggered on the first run on Windows ("Balanced": 3.12 → 3.50 GHz, 12.3%, run flagged). The warmup before the estimate went from 100 to 300 ms, and even so WSL2 still ramped up during the run (3.12 → 3.62 GHz, 16%). Now the warmup goes on until the frequency stops changing: load and an estimate every ~100 ms, until two consecutive ones differ by less than 1% (at least 300 ms, at most 3 s). Measured over 10 runs of bench-core: the drift per run became 0.0 to 1.2% (one at 4.9%) on WSL2, and 0.0 to 2.3% (one at 12.7%) on Windows.
The gate. With a quiet-machine noise model (1.5% between repetitions, 3% between samples, 1% preemptions ×2 to 5, 5 repetitions, bench.selftest):
| result | |
|---|---|
| 100 noise-only comparisons | 0 false failures |
| 100 planted 10% regressions | 98 detected (the 2 missed measured +7.7% and +9.0%, at 98.8% and 98.6% confidence against the 99% required) |
| the naive gate (two medians, 5%) on the same noise | fails identical runs |
On this machine, with real runs (power_gate.sh, 5 repetitions, 5% threshold): 0 false failures in 10, and 8 of 10 regressions of 10% detected. In one of the missed ones, one repetition was disturbed (interval 0.51 .. 3.79) and the gate refused to conclude, which is the requested behavior.
Repeatability (spread.py, 10 runs of bench-core): the < 2% target is not reached on this machine for all benchmarks.
| configuration | spread of the medians (best .. worst benchmark) |
|---|---|
| GCC, WSL2 (before warmup until the frequency stops) | 2.6% .. 54.7% |
| MSVC, native Windows (same) | 10.1% .. 56.4% |
GCC, WSL2, --pin 3 --min-time 1 (same) | 13.5% .. 134.8% (pinning a vCPU in a VM makes it worse) |
| GCC, WSL2, with warmup until the frequency stops | 0.4% .. 14.1% (6 of 10 benchmarks below 2%) |
| MSVC, native Windows, same | 1.3% .. 14.1% (3 of 10 below 2%) |
What remains is not clock drift: on Base64Encode/1024 (GCC), nine runs fall between 93.8 and 94.6 ns (0.85%) and one comes out at 107 ns. It is a disturbed process, and the spec's measure (largest minus smallest) catches it. Measuring in cycles (the Linux counters) does not help in the virtual machine: the spread in cycles came out equal or worse (up to 19%), because the VM's counters are multiplexed.
It is the same as what tools/measure_gate.sh had already measured on this machine (16% to 55%). The effective clock changes by up to 11% between processes (measured when recording the baseline). The criterion is a property of the machine (quiet, fixed frequency, dedicated), and it was not verified on such a machine.
---
Implementation status
| Criterion (spec §7) | Status |
|---|---|
| External dependencies | ✅ none (only Testing) |
ETL_DO_NOT_OPTIMIZE effective at all levels, with a test that would give an impossible number | ✅ GCC -O0/-O1/-O2/-O3/-Os and MSVC /Od/O1/O2/Ox, with the control · ⚠️ /GL (LTCG) not measured · Clang not measured (there is no Clang on this machine) |
| Constant folding: plant detected | ✅ GCC and MSVC |
| Repeatability: 10 runs, median < 2% | ❌ on this machine, for all benchmarks: with warmup until the frequency stops, 0.4% to 14.1% (GCC) and 1.3% to 14.1% (MSVC), with 6 and 3 of 10 benchmarks below 2%. What remains are disturbed processes (see above). Not verified on a quiet fixed-frequency machine |
| Calibration from 1 ns to 1 s | ✅ within 8.3% (GCC) and 2.8% (MSVC) of the reference |
| Statistics: median, p90, p99, min, MAD. Never the mean | ✅ the mean is not computed. Outliers counted by a written rule, never removed |
| Complete environment. Comparison between different environments refused | ✅ CPU, cores, governor/power plan, turbo, affinity, compiler, the unit's real flags (etl_bench_target), optimization, OS and build, clock. Refusal with the fields that differ (bench.selftest, bench.cli) · ⚠️ turbo "unknown" on Windows and on WSL (it is not exposed). Governor "unknown" on WSL |
| Frequency drift detected and flagged | ✅ really detected (Windows, 12.3%). A baseline with drift is refused |
| Hardware counters where available, clean degradation where not | ✅ Linux (perf_event_open: cycles, instructions, branch misses, cache references and misses) · ⚠️ Windows: not implemented: they require administrator (ETW) or a driver, and this machine does not have them to test. Degrades with the reason · macOS: not implemented |
| Gate: planted 10% detected. Noise without false failures in 100 | ✅ 0/100 false. 98/100 detected in the quiet-machine model · ⚠️ on this machine, 8/10 detected (0/10 false) with 5 repetitions |
| HTML report: generates, draws, environment and links to the source | ✅ verified in a browser, light and dark. Every row points to the source, and losses and skipped cases show up |
| Instrument cost < 1 ns per iteration | ✅ 0.28 ns (GCC), 0.61 ns (MSVC) |
| Sanitizers | ✅ bench.selftest and bench.cli clean under ASan+UBSan and TSan (GCC). The repetition children must exit with 0, and a sanitizer report in a child fails the run |
Committed baselines: none. This machine does not produce one that passes the instrument's own criterion (drift of 5.1% and 11.1% over 5 repetitions). See bench/baselines/README.md.
The four old benchmark programs (bench/time, bench/encoding, bench/compression, bench/process) remain as they were, with their ficha and tools/measure_gate.sh. The new model is bench/harness/bench_core.cpp. Their migration was not done. With ETHEREAL_BUILD_BENCH=ON they compile, on GCC, with -Wunused-result warnings that already existed (the library's [[nodiscard]] value ignored) and that do not belong to this module. bench-core compiles on MSVC without /W4, because pch_ethereal.h pulls in library headers with level 4 warnings (C4244, C4146, C4324) that predate it.
The terminal table is plain text and does not go through the Console module: linking it would take away Bench's property of not depending on the library.
---
Out of scope
Profiling (that is the Profiler module), continuous measurement infrastructure or a hosted dashboard, micro-optimization advice, simulating a competitor's workload.