Overview / Developer tools

bench

The measurement harness. It calibrates the batch, warms up until the frequency settles, reports median, p90, p99, minimum and MAD, records the environment and has a statistical regression gate. Includes the <code>etl-bench</code> tool.

Always compiled: part of the core build.Include #include <ethereal/cpp/bench/bench.hpp>

bench.hpp

#include <ethereal/cpp/bench/bench.hpp>

Header for whoever writes benchmarks.

The reports, the statistics and the regression gate are in 'bench_report.hpp', so code that only measures does not compile them.

function

RunBenchMain

Ethereal::Bench#
int RunBenchMain( int argc, char ** argv );

The 'main' of the benchmarks (Ethereal::BenchMain calls it): runs, compares and publishes.

argc
Argument count.
argv
Arguments.
0 on success, 1 on regression or error, 2 on usage error, 3 when refused.

bench_core.hpp

#include <ethereal/cpp/bench/bench_core.hpp>

What a benchmark author uses: the loop, the optimizer barriers and the registry.

Usage:

ETL_BENCH( TimeSuite, NowMonotonic ) { for( auto _ : ETL_BENCH_LOOP ) ETL_DO_NOT_OPTIMIZE( Time::NowMonotonic() ); }

The loop costs one cycle per iteration. The counter lives in a register: the function that closes each batch returns the size of the next one instead of receiving it by reference. By reference the address of the counter escaped, and the "memory" barrier of ETL_DO_NOT_OPTIMIZE forced it to be stored and reloaded on every iteration (measured: 1.38 ns against 0.28 ns per iteration, GCC -O2).

On MSVC, ETL_DO_NOT_OPTIMIZE is not an opaque call for scalars. The classic form (passing the address to a 'noinline' function) failed the test: MSVC /O1 and /O2 see that the function does nothing, even without inlining it, and hoisted 64 dependent multiplications out of the loop (0.7 ns per iteration, impossible). Scalars go through a volatile (also immune to /GL). The rest goes through a library function in another translation unit, which /GL (LTCG) makes transparent again.

What these barriers do not do, as the README repeats:

  • An input that is invariant in the loop may be computed once outside it. Pass the input through ETL_DO_NOT_OPTIMIZE (a non const lvalue is "laundered": the compiler no longer knows its value) or take it from ETL_BENCH_OPAQUE.
  • ETL_CLOBBER_MEMORY only forces the writes to memory whose address escaped. A local buffer whose address never left the function may have its writes removed even with the barrier (measured). Pass the pointer through ETL_DO_NOT_OPTIMIZE before the loop.
function

_ReadWriteBarrier

#
extern "C" void _ReadWriteBarrier( void );

Only the barrier, without the whole '<intrin.h>' (it costs compile time in every unit).

macro

ETL_BENCH_CAT_I_

#
#define ETL_BENCH_CAT_I_( a, b ) a##b

Token concatenation and stringification that expand their arguments first.

function

DoNotOptimize

Ethereal::Bench#
template < class T > ETL_BENCH_FORCEINLINE void DoNotOptimize( const T & Value ) noexcept
function

DoNotOptimize

Ethereal::Bench#
template < class T > ETL_BENCH_FORCEINLINE void DoNotOptimize( T & Value ) noexcept

On a non const lvalue, besides producing it, "launders" it: the compiler no longer knows its value and cannot hoist what depends on it out of the loop.

Value
The value.
function

ClobberMemory

Ethereal::Bench#
ETL_BENCH_FORCEINLINE void ClobberMemory() noexcept

Forces the pending writes to memory that escaped to happen.

function

Opaque

Ethereal::Bench#
template < class T > ETL_BENCH_FORCEINLINE T Opaque( T Value ) noexcept

Returns Value through a path the compiler cannot follow: an input it cannot fold at compile time.

Value
The value.
The same value.
class

SState

Ethereal::Bench#
class SState
struct

SValue

#
C++
struct   SValue {};

Value of the range-for loop variable (empty).

struct

SEnd

#
C++
struct   SEnd {};

End sentinel of the loop.

class

CIter

#
class CIter

Iterator of the loop: counts down the current batch.

constructor

SState

#
explicit SState( Detail::CEngine * pEngine ) noexcept : m_pEngine( pEngine )

Builds the state over the given engine.

function

begin

#
CIter begin() noexcept

Starts the loop.

function

end

#
SEnd end() const noexcept

End of the loop.

function

PauseTiming

#
void PauseTiming() noexcept;

Removes from the time what comes between PauseTiming and ResumeTiming.

Each pair costs two clock reads (tens of ns): use it for setup, not around 1 ns of work.

function

ResumeTiming

#
void ResumeTiming() noexcept;

Resumes the time stopped by PauseTiming.

function

SetBytesPerIteration

#
void SetBytesPerIteration( double dBytes ) noexcept;

Bytes processed per iteration, for the throughput.

function

SetItemsPerIteration

#
void SetItemsPerIteration( double dItems ) noexcept;

Items processed per iteration, for the throughput.

function

SetCounter

#
void SetCounter( const char * sName, double dValue ) noexcept;

A user counter that goes to the report.

function

Skip

#
void Skip( const char * sReason ) noexcept;

This benchmark does not run here (no AVX2, for example). It shows in the report with the reason and never disappears.

function

Engine

#
Detail::CEngine * Engine() const noexcept

The engine.

class

CFixture

Ethereal::Bench#

Base of the fixtures: SetUp and TearDown run once per benchmark, out of the timing.

class CFixture
destructor

~CFixture

#
virtual ~CFixture() = default;

Virtual destructor.

alias

void

Ethereal::Bench#
using FBench = void ( * )( SState & );

Body of a simple benchmark.

alias

void

Ethereal::Bench#
using FBenchArg = void ( * )( SState &, long long );

Body of a benchmark with an argument.

struct

SCase

Ethereal::Bench#
C++
struct   SCase
{
    /// @brief  Label of the case.
    const char *    sLabel;

    /// @brief  Body of the case.
    FBench            pFn;
};

A case of a comparison.

struct

SBenchInfo

Ethereal::Bench#
C++
struct   SBenchInfo
{
    /// @brief  Suite name.
    const char *        sSuite = nullptr;

    /// @brief  Benchmark name.
    const char *        sName = nullptr;

    /// @brief  Source file.
    const char *        sFile = nullptr;

    /// @brief  Source line.
    int                    iLine = 0;

    /// @brief  Body of a simple or fixture benchmark.
    FBench                pFn = nullptr;

    /// @brief  Body of a benchmark with an argument.
    FBenchArg            pArgFn = nullptr;

    /// @brief  Argument values (ETL_BENCH_RANGE).
    const long long *    pArgs = nullptr;

    /// @brief  Number of argument values.
    std::size_t            nArgs = 0u;

    /// @brief  Cases of a comparison.
    const SCase *        pCases = nullptr;

    /// @brief  Number of cases.
    std::size_t            nCases = 0u;

    /// @brief  Flags of the translation unit.
    const char *        sFlags = nullptr;

    /// @brief  Compiler of the translation unit.
    const char *        sCompiler = nullptr;

    /// @brief  Optimization of the translation unit.
    const char *        sOptimized = nullptr;

    /// @brief  Next benchmark in the registry.
    SBenchInfo *        pNext = nullptr;
};

A registered benchmark.

function

RegisterBench

Ethereal::Bench#
void RegisterBench( SBenchInfo * pInfo ) noexcept;

Appends to the registry. Called during static initialization.

pInfo
The benchmark.
function

FirstBench

Ethereal::Bench#
SBenchInfo * FirstBench() noexcept;

The first registered benchmark.

bench_report.hpp

#include <ethereal/cpp/bench/bench_report.hpp>

What comes out of a benchmark and what is done with it.

The statistics, the regression gate and the formats (canonical JSON, CSV, table, HTML).

The mean is never the number. One scheduler preemption pulls it and hides the distribution. The report gives the median (the headline number), p90, p99, minimum and MAD, and the mean is not computed.

The gate compares distributions, not two medians. Hierarchical resampling (bootstrap): the repetitions (separate processes) and, inside each one, the samples. The variation between runs, which on a workstation reaches tens of percent, enters the uncertainty this way, and the gate only fails when it is dConfidence sure that things got worse by more than the threshold. A naive percentage gate fails on noise until someone turns it off, and that is how all of them die.

struct

SEnvironment

Ethereal::Bench#
C++
struct   SEnvironment
{
    /// @brief  CPU model.
    std::string        sCpu;

    /// @brief  Logical cores.
    int                iLogicalCores = 0;

    /// @brief  Physical cores. 0 when unknown.
    int                iPhysicalCores = 0;

    /// @brief  Frequency policy (Linux governor) or power plan (Windows).
    std::string        sGovernor;

    /// @brief  Turbo state.
    std::string        sTurbo;

    /// @brief  Affinity restricted to fewer cores than the system has.
    bool            bPinned = false;

    /// @brief  Cores in the affinity mask.
    int                iAffinityCores = 0;

    /// @brief  Compiler of the benchmark units.
    std::string        sCompiler;

    /// @brief  Flags of the benchmark units.
    std::string        sFlags;

    /// @brief  Whether the benchmark units were optimized.
    std::string        sOptimized;

    /// @brief  Operating system.
    std::string        sOs;

    /// @brief  Architecture.
    std::string        sArch;

    /// @brief  Clock and its resolution.
    std::string        sTimer;

    /// @brief  Estimated effective clock at the start.
    double            dClockStartGHz = 0.0;

    /// @brief  And at the end.
    double            dClockEndGHz = 0.0;

    /// @brief  Clock drift between start and end, in percent.
    double            dDriftPct = 0.0;

    /// @brief  The drift went past the threshold: the run is suspect.
    bool            bDrift = false;

    /// @brief  Cost of the loop with a single ETL_DO_NOT_OPTIMIZE.
    double            dLoopNs = 0.0;

    /// @brief  "disponiveis: ..." or the reason they are not available.
    std::string        sCounters;

    /// @brief  Source revision.
    std::string        sRevision;

    /// @brief  UTC, ISO 8601.
    std::string        sTimestamp;

    /// @brief  What must match for two results to be compared.
    std::string        sFingerprint;
};

Where and how it was measured. A number without this cannot be reproduced and is not published.

struct

SStats

Ethereal::Bench#
C++
struct   SStats
{
    /// @brief  Minimum.
    double            dMin = 0.0;

    /// @brief  Median.
    double            dMedian = 0.0;

    /// @brief  90th percentile.
    double            dP90 = 0.0;

    /// @brief  99th percentile.
    double            dP99 = 0.0;

    /// @brief  Maximum.
    double            dMax = 0.0;

    /// @brief  Median of the absolute deviations from the median (unscaled).
    double            dMad = 0.0;

    /// @brief  Number of samples.
    std::size_t        nSamples = 0u;

    /// @brief  Outliers counted by the rule, never removed.
    std::size_t        nOutliers = 0u;
};

Statistics of the samples of a benchmark.

const

MAD

Ethereal::Bench#
constexpr const char * kOutlierRule = "|x - median| > 5 x MAD (counted, not removed)";

The outlier rule, written in every report.

struct

SHardware

Ethereal::Bench#
C++
struct   SHardware
{
    /// @brief  The counters counted something.
    bool            bValid = false;

    /// @brief  Instructions per iteration.
    double            dInstructions = -1.0;

    /// @brief  Cycles per iteration.
    double            dCycles = -1.0;

    /// @brief  Instructions per cycle.
    double            dIpc = -1.0;

    /// @brief  Branch misses per iteration.
    double            dBranchMisses = -1.0;

    /// @brief  Cache references per iteration.
    double            dCacheReferences = -1.0;

    /// @brief  Cache misses per iteration.
    double            dCacheMisses = -1.0;
};

Hardware counters, per iteration. Negative means not counted.

struct

SResult

Ethereal::Bench#
C++
struct   SResult
{
    /// @brief  "Suite.Name", "Suite.Name/1024", "Suite.Group/case".
    std::string        sName;

    /// @brief  Suite.
    std::string        sSuite;

    /// @brief  Benchmark name.
    std::string        sBench;

    /// @brief  Argument, for ETL_BENCH_ARGS.
    std::string        sArg;

    /// @brief  Comparison group.
    std::string        sGroup;

    /// @brief  Comparison case.
    std::string        sCase;

    /// @brief  The case the others are measured against.
    bool            bBaselineCase = false;

    /// @brief  Source file.
    std::string        sFile;

    /// @brief  Source line.
    int                iLine = 0;

    /// @brief  The reason, when it did not run.
    std::string        sSkipped;

    /// @brief  The reason, when it could not run.
    std::string        sError;

    /// @brief  ns per iteration, per repetition.
    std::vector< std::vector< double > >    aReps;

    /// @brief  Over all the samples.
    SStats            Stats;

    /// @brief  Iterations measured.
    std::uint64_t    uIterations = 0u;

    /// @brief  Final batch size.
    std::size_t        uBatch = 0u;

    /// @brief  Warmup batches thrown away.
    std::size_t        nWarmupBatches = 0u;

    /// @brief  Bytes per iteration, for the throughput.
    double            dBytesPerIteration = 0.0;

    /// @brief  Items per iteration, for the throughput.
    double            dItemsPerIteration = 0.0;

    /// @brief  User counters.
    std::vector< std::pair< std::string, double > >    aCounters;

    /// @brief  Hardware counters.
    SHardware        Hw;

    /// @brief  Work removed or folded, loop removed.
    std::string        sSuspect;

    /// @brief  Median / median of the baseline case. 0 means not applicable.
    double            dRatioToBaseline = 0.0;
};

Result of one benchmark.

struct

SReport

Ethereal::Bench#
C++
struct   SReport
{
    /// @brief  Module name.
    std::string                    sModule;

    /// @brief  Environment of the run.
    SEnvironment                Env;

    /// @brief  Results, in run order.
    std::vector< SResult >        aResults;
};

A report: the module, the environment and the results.

function

Percentile

Ethereal::Bench#
double Percentile( const std::vector< double > & aSorted, double p ) noexcept;

Percentile by linear interpolation between order statistics (Hyndman-Fan type 7, the one of R and NumPy).

aSorted
The samples, sorted.
p
Percentile in [0, 1].
The percentile. 0 for no samples.
function

ComputeStats

Ethereal::Bench#
SStats ComputeStats( std::vector< double > aSamples );

Statistics of the samples.

struct

SCompareOptions

Ethereal::Bench#
C++
struct   SCompareOptions
{
    /// @brief  Regression threshold (0.05 is 5%).
    double            dThreshold = 0.05;

    /// @brief  Confidence needed to declare a regression or an improvement.
    double            dConfidence = 0.99;

    /// @brief  Number of resamples.
    int                iResamples = 2000;

    /// @brief  Seed of the resampling.
    std::uint64_t    uSeed = 0x5eed5eedu;
};

Options of the comparison.

enum

EVerdict

Ethereal::Bench#
C++
enum class   EVerdict
{
    /// @brief  Within the noise, or below the threshold.
    eSame,

    /// @brief  Worse, with the confidence asked.
    eRegression,

    /// @brief  Better, with the confidence asked.
    eImprovement
};

Verdict of a comparison.

struct

SCompareResult

Ethereal::Bench#
C++
struct   SCompareResult
{
    /// @brief  The verdict.
    EVerdict    eVerdict = EVerdict::eSame;

    /// @brief  New median / old median (samples pooled).
    double        dRatio = 1.0;

    /// @brief  Low end of the confidence interval of the ratio.
    double        dLow = 1.0;

    /// @brief  High end of the confidence interval of the ratio.
    double        dHigh = 1.0;

    /// @brief  Fraction of the resamples with ratio > 1 + threshold.
    double        dProbWorse = 0.0;

    /// @brief  And with ratio < 1 / (1 + threshold).
    double        dProbBetter = 0.0;

    /// @brief  Some side has fewer than 3 repetitions.
    bool        bFewRepetitions = false;
};

Result of a comparison.

function

CompareDistributions

Ethereal::Bench#
SCompareResult CompareDistributions( const std::vector< std::vector< double > > & aOld, const std::vector< std::vector< double > > & aNew, const SCompareOptions & Options );

Compares two distributions (ns per iteration, lower is better).

aOld
Old samples, per repetition.
aNew
New samples, per repetition.
Options
Threshold, confidence, resamples and seed.
The verdict, the ratio and its interval.
function

EnvironmentDifferences

Ethereal::Bench#
std::vector< std::string > EnvironmentDifferences( const SEnvironment & a, const SEnvironment & b );

The environment fields that differ (empty means comparable).

function

ComputeFingerprint

Ethereal::Bench#
std::string ComputeFingerprint( const SEnvironment & Env );

The fingerprint: a hash of the fields that make two numbers comparable.

function

IsDrift

Ethereal::Bench#
bool IsDrift( double dStartGHz, double dEndGHz, double dThresholdPct, double * pPct ) noexcept;

Did the clock drift go past the threshold?

dStartGHz
Clock at the start.
dEndGHz
Clock at the end.
dThresholdPct
Threshold in percent.
pPct
Receives the drift in percent. May be null.
true when the drift is above the threshold.
struct

SGateOptions

Ethereal::Bench#
C++
struct   SGateOptions
{
    /// @brief  Options of each comparison.
    SCompareOptions        Compare;

    /// @brief  Template with {old} and {new}. Empty means no link.
    std::string            sCommitUrl;
};

Options of the gate.

function

GateCompare

Ethereal::Bench#
int GateCompare( const SReport & Base, const SReport & Candidate, const SGateOptions & Options, std::string * pText );

The gate: compares a candidate report against the baseline.

Base
Baseline report.
Candidate
New report.
Options
Gate options.
pText
Receives the text report. May be null.
0 with no regression, 1 on regression or a missing benchmark, 3 when refused (different environments).
const

kJsonFormat

Ethereal::Bench#
constexpr const char * kJsonFormat = "ethereal-bench/1";

Identifier of the JSON format, written in the "format" field.

function

ToJson

Ethereal::Bench#
std::string ToJson( const SReport & Report );

The canonical JSON.

function

FromJson

Ethereal::Bench#
bool FromJson( const std::string & sJson, SReport * pOut, std::string * pError );

Reads the canonical JSON. The statistics are recomputed from the samples.

sJson
The text.
pOut
Receives the report.
pError
Receives the error, with the position. May be null.
false when the text is not a valid report.
function

ToCsv

Ethereal::Bench#
std::string ToCsv( const SReport & Report );

CSV (RFC 4180), one line per benchmark.

function

ToTable

Ethereal::Bench#
std::string ToTable( const SReport & Report );

The terminal table.

struct

SHtmlOptions

Ethereal::Bench#
C++
struct   SHtmlOptions
{
    /// @brief  Page title.
    std::string                    sTitle = "Ethereal: measurements";

    /// @brief  Base URL. The relative file and "#L<line>" are appended.
    std::string                    sSourceUrl;

    /// @brief  Prefixes to strip from the path (one per machine: C:/..., /mnt/c/...).
    std::vector< std::string >    aSourceRoots;
};

Options of the HTML page.

function

ToHtml

Ethereal::Bench#
std::string ToHtml( const std::vector< SReport > & aReports, const SHtmlOptions & Options );

The HTML page of one or more reports.

struct

SRunOptions

Ethereal::Bench#
C++
struct   SRunOptions
{
    /// @brief  Globs. A '-' in front excludes.
    std::vector< std::string >    aFilters;

    /// @brief  Minimum measuring time per benchmark.
    double            dMinTimeS = 0.5;

    /// @brief  Ceiling (only passed to reach the minimum sample count).
    double            dMaxTimeS = 10.0;

    /// @brief  Target duration of each batch (sample).
    double            dWindowNs = 2.0e6;

    /// @brief  Minimum number of samples.
    std::size_t        nMinSamples = 20u;

    /// @brief  Minimum when one batch alone already passes the window.
    std::size_t        nMinSamplesSlow = 5u;

    /// @brief  Maximum number of samples.
    std::size_t        nMaxSamples = 1000u;

    /// @brief  Maximum warmup time.
    double            dWarmupMaxS = 0.5;

    /// @brief  Warmed up: three batches in a row within 2%.
    double            dStableTolerance = 0.02;

    /// @brief  Read the hardware counters.
    bool            bCounters = true;

    /// @brief  Clock drift that marks the run, in percent.
    double            dDriftThresholdPct = 5.0;

    /// @brief  Source revision.
    std::string        sRevision;

    /// @brief  Module name.
    std::string        sModule;

    /// @brief  No progress in the terminal.
    bool            bQuiet = false;
};

Options of a run.

function

RunBenchmarks

Ethereal::Bench#
SReport RunBenchmarks( const SRunOptions & Options );

Runs the registered benchmarks that pass the filter, in this process, one repetition.

function

CaptureEnvironment

Ethereal::Bench#
SEnvironment CaptureEnvironment( const SRunOptions & Options );

Only the environment (includes estimating the clock and the cost of the loop).