Overview / Math, game & observability

stats

Descriptive statistics over sample streams.

Always compiled: part of the core build.Include #include <ethereal/cpp/stats/stats_inc.hpp>C layer

stats_inc.hpp

#include <ethereal/cpp/stats/stats_inc.hpp>

Aggregate entry point of the Stats module.

Descriptive statistics over a stream of measurements. It exists because they were already written by hand inside CProfilerManager (mean, M2, minimum, maximum and a queue of 254 samples for p50/p90/p99) where nobody else could use them.

The numeric decisions (Welford instead of a sum of squares, both variances exposed, zero instead of NaN, the exact percentile formula, and the histogram left out on purpose) are written out at the top of stats.hpp. A wrong number in statistics does not show up as a failure: it shows up as a plausible number.

Which one to use:

  • Ethereal::Stats::CRunningStats : count, minimum, maximum, sum, mean and variance of a stream, in constant memory. It keeps no samples, so it answers no median or percentile.
  • Ethereal::Stats::CSampleWindow : the last N samples, with exact percentiles over them.

The two go together: the accumulator covers the whole history, the window covers the recent past. A report that shows both must say which is which, since they disagree on purpose.

Including this header brings the whole module.

stats.hpp

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

Descriptive statistics: running moments, sliding window moments and exact percentiles over a sample window.

This module exists because statistics were already written in the library by hand, locked inside their users: CProfilerManager carries mean, M2, minimum, maximum and a queue of 254 samples to compute p50/p90/p99, and none of it is reachable by anyone else. A wrong number in statistics does not show up as a failure, it shows up as a plausible number, so the choices are written here.

1. Mean and variance use Welford, not a sum of squares. The naive form, sum(x^2)/n - mean^2, subtracts two large and almost equal numbers. With samples far from zero (and times in microseconds are exactly that) the cancellation eats the significant digits and the variance comes out wrong, sometimes negative. Welford updates the mean and the sum of deviations without ever forming that pair, and costs the same two operations per sample.

2. Both variances are exposed, and neither hides behind the other. Variance divides by (n-1): the sample estimate, for when the samples are a slice of a process that goes on (measuring 200 runs of a function that will run millions of times). PopulationVariance divides by n, for when the samples are the whole population. Picking one silently is a common and invisible mistake: the difference vanishes when n is large and bites when n is small, which is exactly when someone looks at the number.

3. Without samples everything is zero, not NaN. NaN was refused because it propagates: it taints every following computation without complaint, and ends up written as "nan" in a CSV that someone later loads in a spreadsheet. Zero is just as false, but it does not spread, and Count()/IsEmpty() are right there to settle the doubt.

4. The percentile uses linear interpolation between the order statistics, with the formula written out in CSampleWindow::Percentile. Percentile has no single definition (at least nine are in use), so saying "p99" without saying which identifies no number at all.

5. Not here: bucket histograms. They are the usual way to get a percentile without keeping samples, and the usual way to get it wrong: the result depends on where the buckets were cut, and that choice cannot be undone after the data was aggregated. CSampleWindow keeps the samples and gives the exact percentile of the window. When there is a real need to aggregate without keeping samples, the histogram comes with limits declared by the caller, not guessed here.

Nothing here is guaranteed to be thread safe.

class

CRunningStats

Ethereal::Stats#

Accumulates count, minimum, maximum, sum, mean and variance of a stream of samples, in constant memory.

class CRunningStats final

Does not keep the samples. A million values take the same space as two, which is why it fits whatever runs all the time: frame time, task duration, packet size.

The price of not keeping them is not being able to answer median or percentile, which need the samples. That is what CSampleWindow is for, and the two are meant to go together: the accumulator covers the whole history, the window covers the recent past exactly.

Not guaranteed to be thread safe. To accumulate on several threads, give each one an accumulator and join them with Merge at the end. That is what it is for, and it is cheaper than fighting over a lock per sample.
constructor

CRunningStats

#
CRunningStats() noexcept;

Creates an empty accumulator.

function

Add

#
void Add( const ETL_DOUBLE dValue ) noexcept;

Adds one sample.

function

Add

#
void Add( std::span< const ETL_DOUBLE > Values ) noexcept;

Adds several samples.

function

Merge

#
void Merge( const CRunningStats & Other ) noexcept;

Joins another accumulator into this one, as if its samples had been added here.

Uses Chan's parallel form, which combines two means and two sums of deviations without reprocessing any sample. That is what allows accumulating per thread, without a lock, and joining once at the end.

Joining an empty accumulator does nothing, and joining with itself is not allowed.

function

Reset

#
void Reset() noexcept;

Returns to the initial state.

function

Count

#
ETL_UINT64 Count() const noexcept;

Number of samples.

function

IsEmpty

#
bool IsEmpty() const noexcept;

true when there are no samples.

function

Min

#
ETL_DOUBLE Min() const noexcept;

Smallest sample.

function

Max

#
ETL_DOUBLE Max() const noexcept;

Largest sample.

function

Sum

#
ETL_DOUBLE Sum() const noexcept;

Sum of the samples.

function

Mean

#
ETL_DOUBLE Mean() const noexcept;

Mean of the samples.

function

Variance

#
ETL_DOUBLE Variance() const noexcept;

Sample variance, divided by (n-1).

Zero with fewer than two samples: with one there is no spread to estimate.

function

StdDev

#
ETL_DOUBLE StdDev() const noexcept;

Sample standard deviation: the square root of Variance.

function

PopulationVariance

#
ETL_DOUBLE PopulationVariance() const noexcept;

Population variance, divided by n.

function

PopulationStdDev

#
ETL_DOUBLE PopulationStdDev() const noexcept;

Population standard deviation: the square root of PopulationVariance.

class

CWindowMoments

Ethereal::Stats#
class CWindowMoments final
function

Add

#
void Add( const ETL_DOUBLE x ) noexcept

A sample enters the window.

function

Remove

#
void Remove( const ETL_DOUBLE x ) noexcept

A sample that entered before leaves. Removing from an empty window does nothing.

function

Merge

#
void Merge( const CWindowMoments & Other ) noexcept

Joins another window into this one (Chan's parallel form).

function

Reset

#
void Reset() noexcept

Empties the window.

function

Count

#
ETL_UINT64 Count() const noexcept

Number of samples in the window.

function

Mean

#
ETL_DOUBLE Mean() const noexcept

The mean. Zero without samples (decision 3).

function

M2

#
ETL_DOUBLE M2() const noexcept

The sum of squared deviations (Welford's M2).

function

PopulationVariance

#
ETL_DOUBLE PopulationVariance() const noexcept

Population variance (divided by n). Zero without samples.

function

Variance

#
ETL_DOUBLE Variance() const noexcept

Sample variance (divided by n - 1). Zero with fewer than two samples.

class

CSampleWindow

Ethereal::Stats#

Keeps the last N samples and answers exact percentiles over them.

class CSampleWindow final

Fixed capacity, set at construction: one allocation, none after. When full, the oldest sample gives way. The same idea as Ethereal::Containers::CRingBuffer, with the math on top.

The window is a slice, and the slice is the difference that matters. A CRunningStats next to it covers the whole history, and the two disagree on purpose: the all time mean does not see the degradation of the last hours, and the median of the window does not know how yesterday was. A report that mixes both without saying which is which (CProfilerManager did exactly that, the mean of all calls next to the percentiles of the last 254) invites comparing numbers that do not cover the same period.

Not guaranteed to be thread safe.
constructor

CSampleWindow

#
explicit CSampleWindow( const std::size_t uCapacity );

Creates the window with a fixed capacity.

uCapacity
Number of samples kept. Zero is treated as 1: a window that keeps nothing answers nothing, and would be a silent error instead of a window.
function

Add

#
bool Add( const ETL_DOUBLE dValue );

Adds a sample, dropping the oldest one when needed.

dValue
The sample.
true when something was dropped to make room.
function

Clear

#
void Clear() noexcept;

Empties the window. The capacity does not change, and the memory is kept.

function

Count

#
std::size_t Count() const noexcept;

Number of samples in the window.

function

Capacity

#
std::size_t Capacity() const noexcept;

Fixed capacity.

function

IsEmpty

#
bool IsEmpty() const noexcept;

true when the window is empty.

function

IsFull

#
bool IsFull() const noexcept;

true when the window is full.

function

Percentile

#
ETL_DOUBLE Percentile( const ETL_DOUBLE dPercent ) const;

Percentile dPercent of the window, by linear interpolation.

With the n samples sorted in s[0..n-1]:

position = ( dPercent / 100 ) ( n - 1 ) low = floor( position ) fraction = position - low value = s[ low ] + fraction ( s[ low + 1 ] - s[ low ] )

The most widespread convention (the same as numpy.percentile and the spreadsheet PERCENTILE.INC), chosen so the number can be compared with another tool's without translation.

dPercent is clamped to [0, 100]. By construction, 0 gives the minimum and 100 gives the maximum.

dPercent
The position, in [0, 100].
The interpolated value. Zero on an empty window.
Sorts a copy on each call. For several percentiles of the same window, use PercentileMany, which sorts only once.
The value returned may not be an observed sample: between two neighbours it is the interpolated point. With few samples that is the rule, not the exception.
function

PercentileMany

#
bool PercentileMany( std::span< const ETL_DOUBLE > Percents, std::span< ETL_DOUBLE > OutValues ) const;

Several percentiles at once, sorting a single copy.

Percents
The requested positions, in [0, 100]. Need not be sorted.
OutValues
Where to write, in the same order as Percents. Must have the same size.
false when the sizes do not match. Nothing is written.
function

Median

#
ETL_DOUBLE Median() const;

The median of the window: Percentile at 50.

function

Min

#
ETL_DOUBLE Min() const noexcept;

Smallest and largest sample of the window, without sorting.

function

Max

#
ETL_DOUBLE Max() const noexcept;
function

Mean

#
ETL_DOUBLE Mean() const noexcept;

Mean of the samples in the window.

A direct sum, not Welford: the window has a known and bounded size, so there is no long accumulation where the error would add up.

operator

operator[]

#
ETL_DOUBLE operator[]( const std::size_t uIndex ) const noexcept;

Logical access: index 0 is the oldest sample still in the window.

The index must be smaller than Count.