Skip to content

Statistics and Measurement

Penza edited this page Nov 28, 2026 · 19 revisions

πŸ“Š Statistics and Measurement

Introduced in v1.2.0. The harness returns every retained successful sample so you can inspect the distribution, not just a summary of it.

New Routines Report Warning


Why a single measurement is not enough

One timing sample tells you what happened once. It cannot tell you whether that number is stable, whether the machine was busy, or whether you would get the same answer again.

VBA timing samples are commonly right-skewed because scheduling, calculation, events, and host activity add one-sided delays. The exact distribution is workload- and environment-specific.

Important

Do not report the arithmetic mean by itself.

A delayed sample can move the mean materially while moving the median less. A mean without the sample count and spread cannot show whether the run was stable.

Report the median and the fastest observed run. Use the mean only alongside sample count and spread, and keep the underlying vector.


The harness

MeasureProcedure

Function MeasureProcedure( _
    ByVal ProcedureName As String, _
    Optional ByVal Iterations As Long = 30, _
    Optional ByVal WarmupIterations As Long = 3, _
    Optional ByVal iMethod As cPM_TimerMethod = cPM_MethodQPC, _
    Optional ByRef FailedReadsOut As Long, _
    Optional ByRef LastFailureStatusOut As cPM_ReadStatus, _
    Optional ByRef RejectedSamplesOut As Long) As Double()

Runs a named procedure repeatedly and returns every retained measured elapsed value. Every element was measured on the backend you requested. The vector can be shorter than the requested iteration count, because a cycle whose endpoint read failed and a cycle whose requested backend fell back both contribute nothing.

Dim cPM As cPerformanceManager
Dim S() As Double

Set cPM = New cPerformanceManager
S = cPM.MeasureProcedure("RebuildPivotCache", 30, 3)

Debug.Print cPM.Stats_Text(S, "Pivot rebuild")

Warm-up iterations run first and are discarded. They reduce common first-run effects; they do not guarantee identical cache, calculation, or workbook state.

Caution

MeasureProcedure executes the name it is given. Passing a name that came from a worksheet cell, a configuration sheet or a file lets that source run arbitrary code inside your VBA project.

Qualification narrows a different risk β€” a same-named procedure in another open workbook being selected β€” but not this one. Validating the string would not help either: any syntactically valid procedure name is executable by design, so a filter would look like protection without being any.

Pass literals, or names your own code controls.

Warning

The harness contract is a Public Sub in a standard module.

MeasureProcedure supplies only the macro name and expects no return value or arguments. Class methods, Private procedures, and procedures hidden by Option Private Module are outside this supported target shape.

Note

Application.Run adds a dispatch cost to every sample. Measure it on your own machine rather than assuming a figure. The harness suits work measured in milliseconds or longer.

MeasureOverhead_Samples measures the backend timing cycle only and does not dispatch through Application.Run, so it is not a matched baseline for MeasureProcedure. Use MeasureBaseline instead β€” see below.

Microsoft's host API reference is Application.Run; the narrower no-argument Public Sub target shape documented here is this component's harness contract.

Unqualified names are quoted and qualified with ThisWorkbook, with embedded apostrophes escaped, so a host named O'Brien.xlsm resolves without help. Leading and trailing spaces are trimmed from the procedure name; tabs, carriage returns and line feeds are not.

Measurement runs on an isolated worker instance, so your own session, checkpoints, and run label are never disturbed.

Because that worker is released before the vector is returned, its read outcome cannot be reached through LastReadStatus. Two optional arguments report it:

Dim S() As Double
Dim Failed As Long, Rejected As Long
Dim Status As cPM_ReadStatus

S = cPM.MeasureProcedure("MyWorkload", 30, 3, cPM_MethodQPC, _
                         Failed, Status, Rejected)

If Failed < 0 Then
    Debug.Print "No evidence published - read Err.Number instead."
ElseIf Rejected > 0 Then
    Debug.Print Rejected & " cycle(s) fell back and were rejected."
ElseIf Failed > 0 Then
    Debug.Print Failed & " read(s) failed - inspect status before use."
End If

Measured-cycle classification

Every measured cycle ends in exactly one of three states.

State What happened Counted in
Retained The requested backend started and the endpoint read succeeded the returned vector
Rejected The requested backend could not start, so the session fell back to backend 2 RejectedSamplesOut
Failed The backend started, but the endpoint read failed FailedReadsOut

The two losses are counted separately because their remedies differ. A failed read says this host's clock is unreliable; a rejection says this host cannot start the backend you asked for.

Important

Existing callers: fallback samples are now rejected. A cycle that falls back no longer contributes to the vector. On a host that cannot start the requested backend, a non-strict run returns a shorter vector or raises ERR_CPM_MEASURE_NO_VALID_SAMPLES, and a rejected cycle does not dispatch the workload β€” so a procedure with side effects executes fewer times than Iterations requested.

Sample-count equation

Iterations = Stats_Count(ReturnedVector)
           + measured endpoint failures
           + RejectedSamplesOut

Measured endpoint failures are derived rather than published:

measured endpoint failures
  = Iterations
  - Stats_Count(ReturnedVector)
  - RejectedSamplesOut

FailedReadsOut can exceed that derived count, because it includes warm-up endpoint failures. RejectedSamplesOut excludes warm-up fallback. The asymmetry is deliberate: a warm-up read that fails is evidence the host cannot be measured reliably, whereas a warm-up fallback determines no returned observation, since every measured iteration starts and validates a session of its own.

A failed read still contributes no sample. Storing its zero would make the failure look like the fastest run in the set.

Important

Existing callers: a negative count means no evidence. FailedReadsOut and RejectedSamplesOut are -1 until the run reaches a publication point β€” a normal return, or the aggregate ERR_CPM_MEASURE_NO_VALID_SAMPLES raise, which publishes before raising.

If FailedReadsOut < 0 Then
    'This run published nothing. Read Err.Number instead.
End If

A negative count does not mean nothing failed; it means nothing was recorded. LastFailureStatusOut is meaningful only while the counts are non-negative.


MeasureBaseline

Function MeasureBaseline( _
    ByVal EmptyProcedureName As String, _
    Optional ByVal Iterations As Long = 30, _
    Optional ByVal WarmupIterations As Long = 3, _
    Optional ByVal iMethod As cPM_TimerMethod = cPM_MethodQPC, _
    Optional ByRef FailedReadsOut As Long, _
    Optional ByRef LastFailureStatusOut As cPM_ReadStatus, _
    Optional ByRef RejectedSamplesOut As Long) As Double()

Runs an empty procedure through the same dispatch path as a real workload, so its median is a dispatch-matched baseline estimate designed for subtraction.

Dim Work() As Double, Base() As Double

Work = cPM.MeasureProcedure("MyWorkload", 30, 3)
Base = cPM.MeasureBaseline("cPM_BaselineEmpty", 30, 3)

Debug.Print "Net: " & (cPM.Stats_Median(Work) - cPM.Stats_Median(Base))

Subtract medians, not means. Both vectors are right-skewed, and subtracting two means compounds the contamination in each.

For work close to the observed floor, the difference can be zero or negative because two independently sampled distributions are being summarized and subtracted. Treat that as "not resolved above baseline," not negative runtime.

Note

You supply the empty procedure. Application.Run cannot reach anything in a module declared Option Private Module, which the companion TW module uses to keep its internals out of the Macro dialog β€” so a bundled empty Sub would need a third file containing two lines. Add this once, anywhere in a standard module:

Public Sub cPM_BaselineEmpty()
End Sub

MeasureBaseline delegates to MeasureProcedure, so qualification, isolation, classification and failure handling are identical by construction. It forwards all three evidence outputs from the delegated run, which is what lets you check validity before subtracting. A clean 30-sample workload compared against a baseline quietly reduced to 4 samples is not a comparison:

Dim WFailed As Long, WRejected As Long, BFailed As Long, BRejected As Long
Dim WStatus As cPM_ReadStatus, BStatus As cPM_ReadStatus

Work = cPM.MeasureProcedure("MyWorkload", 30, 3, cPM_MethodQPC, _
                            WFailed, WStatus, WRejected)
Base = cPM.MeasureBaseline("cPM_BaselineEmpty", 30, 3, cPM_MethodQPC, _
                           BFailed, BStatus, BRejected)

'A negative count means that run published no evidence at all
If WFailed < 0 Or BFailed < 0 Then
    Debug.Print "A run ended before classifying anything - inspect Err."

'Fallback rejections mean the two vectors came from different clocks
ElseIf WRejected > 0 Or BRejected > 0 Then
    Debug.Print "Backend fallback rejected samples - not a matched pair."

'Native read failures degrade both vectors without changing their backend
ElseIf WFailed > 0 Or BFailed > 0 Then
    Debug.Print "Read failures occurred (" & WFailed & " workload, " & _
                BFailed & " baseline) - check the status first."

'A baseline far shorter than the workload is not a comparable sample
ElseIf cPM.Stats_Count(Base) < cPM.Stats_Count(Work) \ 2 Then
    Debug.Print "Baseline is badly degraded - do not subtract."

Else
    Debug.Print "Net: " & (cPM.Stats_Median(Work) - cPM.Stats_Median(Base))
End If

FailedReadsOut includes warm-up failures, so a small non-zero value does not necessarily mean a measured sample was lost. Treat it as a reason to inspect LastFailureStatusOut, not as a count of missing elements.

Measure the baseline on the same backend as the workload. A baseline rejected for fallback while the workload was not is not a matched pair, however close the medians look.


MeasureOverhead_Samples

Function MeasureOverhead_Samples( _
    Optional ByVal Iterations As Long = 1000, _
    Optional ByVal WarmupIterations As Long = 10, _
    Optional ByVal iMethod As cPM_TimerMethod = cPM_MethodQPC, _
    Optional ByRef FailedReadsOut As Long, _
    Optional ByRef LastFailureStatusOut As cPM_ReadStatus, _
    Optional ByRef RejectedSamplesOut As Long) As Double()

Measures the cost of the timing machinery itself β€” a near-empty StartTimer / ElapsedSeconds cycle. It uses the same three-state classification, the same count equation with cycles in place of iterations, and the same non-publication sentinel as MeasureProcedure.

Dim Overhead() As Double
Overhead = cPM.MeasureOverhead_Samples(1000, 10)

Debug.Print "Observed empty-cycle floor: " & _
            Format$(cPM.Stats_Min(Overhead), "0.000000000") & " s"

Tip

The minimum of this vector is your observed empty-cycle floor, not the clock's resolution. It contains the start read, the end read, class dispatch and loop overhead. Run this on each target environment before benchmarking anything small. QPC_Get_SystemTickInterval is only the reciprocal of the reported QPC frequency; it is not proof of effective VBA measurement resolution.

Important

Existing callers: overhead cycles are classified too. A cycle whose requested backend fell back is rejected rather than retained, so an overhead figure can no longer describe a different clock than the one asked for. On a host that cannot start the requested backend, a non-strict run returns a shorter vector or raises ERR_CPM_MEASURE_NO_VALID_SAMPLES.

Check the evidence before reading the floor. A rejected cycle means the floor below was not measured on the backend you requested:

Dim Overhead() As Double, Failed As Long, Rejected As Long
Dim Status As cPM_ReadStatus

Overhead = cPM.MeasureOverhead_Samples(1000, 10, cPM_MethodQPC, _
                                       Failed, Status, Rejected)

If Failed < 0 Then
    Debug.Print "The run published no evidence - read Err, not these counts."
ElseIf Rejected > 0 Then
    Debug.Print Rejected & " cycle(s) fell back - the floor is not the " & _
                "requested backend's."
Else
    Debug.Print "Observed empty-cycle floor: " & _
                Format$(cPM.Stats_Min(Overhead), "0.000000000") & " s"
End If

The statistics

Every routine accepts a timing observation vector β€” a Double() of finite, non-negative values. The vector is yours to keep, export and post-process; it simply has to remain a set of elapsed times.

From v1.4.1 (#32), the domain is bounded at 1E+15 seconds (about 31.7 million years). Within it no statistic can overflow; a larger value is rejected. v1.4.0 and earlier accept values up to 1E+300, so an extreme vector such as [0, 1E+200] can overflow the standard deviation.

Note

Out-of-domain data is rejected at a single gate with ERR_CPM_STATS_OUT_OF_DOMAIN, naming the offending index and reason.

Not because Stats_Min breaks on a negative number β€” it does not. Because a negative value means the vector is not a timing vector, so every figure computed from it would describe something you did not intend. Zero is in domain: an operation can genuinely be too fast to resolve.

Member Returns
Stats_Median(S) Median. The headline statistic
Stats_Min(S) Smallest observed value; useful as an empirical floor, but sensitive to timer quantization and noise
Stats_Max(S) Largest observed value
Stats_Percentile(S, P) Nearest-rank percentile, P in 0–100
Stats_Mean(S) Arithmetic mean
Stats_StdDev(S) Sample standard deviation, Nβˆ’1 divisor
Stats_CoefficientOfVariation(S) StdDev Γ· positive mean; dimensionless relative spread, interpreted in workload context
Stats_IsContaminated(S, [CvThreshold]) True when CV exceeds the threshold (default 0.25) or is undefined
Stats_Count(S) Element count. Returns 0 for an uninitialised array
Stats_Text(S, [Caption]) Formatted multiline summary

Design guarantees

  • Nearest-rank percentiles. No interpolation, so every value returned is a measurement that actually happened.
  • Your array is never reordered. Median and percentile sort a private copy.
  • Sample standard deviation. The Nβˆ’1 divisor is used because these are samples of a process, not a complete population. A single sample returns 0.
  • Stats_Count tolerates an uninitialised array. Every other routine raises on an empty vector.

Reading the output

TIMING STATISTICS | Pivot rebuild
Samples           : 30
Median            : 0.412883100 s
Min               : 0.401220400 s
P95               : 0.498771300 s
Max               : 0.612004900 s
Mean              : 0.421994700 s
StdDev            : 0.038112600 s
CoeffOfVariation  : 0.0903

Stats_Text lists median and minimum first and the mean last, deliberately.

Coefficient of variation

CV Interpretation
< 0.05 Low relative dispersion under the built-in heuristic
0.05 – 0.25 Moderate relative dispersion; compare with context and repeated runs
> 0.25 Flagged by the default heuristic; investigate and re-run

When CV exceeds the threshold, Stats_Text appends:

WARNING           : high variance; re-run on a quieter machine.

Note

This is a heuristic, not a statistical test. It flags runs worth repeating; it does not prove a result is wrong.

P95 against the median

The gap is a useful tail diagnostic, not proof of a particular cause:

  • P95 close to the median β€” limited upper-tail spread in this sample.
  • P95 several multiples higher β€” a heavy upper tail worth investigating; inspect the workload and environment before using any summary.

Comparing two implementations

Dim A() As Double, B() As Double
Dim MedianA As Double, MedianB As Double

A = cPM.MeasureProcedure("Approach_LoopCells", 20, 3)
B = cPM.MeasureProcedure("Approach_ArrayBulk", 20, 3)

Debug.Print cPM.Stats_Text(A, "Loop over cells")
Debug.Print cPM.Stats_Text(B, "Bulk array")

MedianA = cPM.Stats_Median(A)
MedianB = cPM.Stats_Median(B)
If MedianB > 0# Then
    Debug.Print "Median speedup: " & Format$(MedianA / MedianB, "0.00") & "x"
Else
    Debug.Print "Median speedup unresolved: comparison median is zero."
End If

Important

Compare medians, report both distributions, and check both runs with the same heuristic and environment controls.

If either vector is flagged, re-run both before drawing a conclusion. A CV flag is a reason to investigate, not a statistical acceptance/rejection test.


Working with the raw vector

Because the harness returns a plain Double(), the samples are yours:

Dim S() As Double
Dim i As Long

S = cPM.MeasureProcedure("MyWorkload", 100, 10)

'Write every sample to a worksheet for inspection
For i = LBound(S) To UBound(S)
    Sheet1.Cells(i, 1).Value = S(i)
Next i

'Or drive your own analysis
If cPM.Stats_Percentile(S, 99#) > 2# * cPM.Stats_Median(S) Then
    Debug.Print "Tail is more than twice the median - investigate."
End If

Errors

Condition Error constant
Statistics requested for an empty or uninitialised vector ERR_CPM_STATS_NO_SAMPLES
Percentile outside 0–100 ERR_CPM_STATS_BAD_PERCENTILE
Blank procedure name passed to MeasureProcedure ERR_CPM_MEASURE_BLANK_PROC
Coefficient of variation undefined because mean is not positive ERR_CPM_STATS_UNDEFINED_CV
Negative contamination threshold ERR_CPM_STATS_BAD_CV_THRESHOLD
Blank baseline procedure name ERR_CPM_MEASURE_NO_BASELINE
No measured sample retained β€” every cycle failed or was rejected ERR_CPM_MEASURE_NO_VALID_SAMPLES
Negative or non-finite observation (from v1.4.1: negative, NaN, or above 1E+15 s) ERR_CPM_STATS_OUT_OF_DOMAIN

Any error raised by the measured procedure itself propagates to the caller after the worker instance has been cleaned up.


Relationship to OverheadMeasurement_*

The older OverheadMeasurement_Seconds and OverheadMeasurement_Text members remain and return the arithmetic mean only. OverheadMeasurement_Seconds delegates to MeasureOverhead_Samples and averages the retained vector, so the mean is computed over what actually survived rather than over the requested iteration count.

Important

Existing callers: the numeric helper can now raise. OverheadMeasurement_Seconds previously always returned a Double. It raises ERR_CPM_MEASURE_NO_VALID_SAMPLES when no cycle survives.

OverheadMeasurement_Text traps only that condition and renders undefined (<original description>), so an all-fallback run reads differently from an all-failed one. Every other error propagates unchanged: an invalid argument is not an undefined measurement.

They are retained for continuity. For new work prefer:

Debug.Print cPM.Stats_Text(cPM.MeasureOverhead_Samples(1000, 10))

which reports the same class of near-empty timing cycle with the full retained distribution and a dispersion heuristic.


See also


πŸ“† Changed in v1.4.0

This section records the changes released in v1.4.0, certified on the stated 64-bit Excel host; real Office 32-bit execution remains unverified. See published evidence. The authoritative ledger is CHANGELOG.md.

Area v1.3.0 v1.4.0
Vector homogeneity A non-strict start fallback was retained, so one vector could mix backends A fallback cycle is rejected; every retained element used the requested backend (#23)
Evidence outputs MeasureProcedure only, two outputs All three harness members, three outputs each (#23, #27, #28)
Count equation Two terms Three terms, adding rejections
Unpublished evidence Outputs read 0, indistinguishable from a clean run Outputs read -1 until a publication point (#23)
Workbook qualification Apostrophes unescaped Escaped; outer spaces trimmed (#25)
Legacy overhead mean Failed reads added as zeros, denominator unchanged Mean of retained samples; can raise (#24)
Legacy overhead text Propagated every error Renders undefined (...) for the no-valid-sample condition only (#24)

The v1.3.0 behaviour above is historical. Sections marked Existing callers in the text are the changes that can alter what working code does.

Clone this wiki locally