perf_hooks: implement Histogram meanCI API

Signed-off-by: James M Snell <jasnell@gmail.com>
Assisted-by: Opencode
PR-URL: https://github.com/nodejs/node/pull/65606
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Vinícius Lourenço Claro Cardoso <contact@viniciusl.com.br>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
This commit is contained in:
James M Snell authored and Antoine du Hamel committed 2026-09-15 10:49:28 +02:00
1 parent 1627fd6561
commit ebcfec2f0c
5 files changed
+208 -18

No files matched your search

+35
View File
@@ -2284,6 +2284,41 @@ added: v11.10.0
The mean of the recorded event loop delays.
### `histogram.meanCI([options])`
<!-- YAML
added: REPLACEME
-->
* `options` {Object}
* `confidence` {number} The confidence level for the interval, between
0 and 1 (exclusive). **Default:** `0.95`.
* Returns: {Object}
* `mean` {number} The mean estimate, equivalent to `histogram.mean`.
* `lower` {number} The lower bound of the confidence interval.
* `upper` {number} The upper bound of the confidence interval.
Returns a two-sided confidence interval for the mean using Student's
t-distribution and the sample standard error. A higher confidence level
produces a wider interval. This interval assumes that samples are independent
and approximately normally distributed, although the approximation is robust
for sufficiently large samples.
The result reflects the histogram's configured precision and is calculated
from the values represented by its buckets. With fewer than two recorded
values, `lower` and `upper` are `NaN`. When all recorded values are equal,
`lower` and `upper` equal `mean`.
```js
const { createHistogram } = require('node:perf_hooks');
const h = createHistogram();
for (let i = 1; i <= 100; i++) h.record(i);
const { mean, lower, upper } = h.meanCI();
console.log(`mean=${mean}, 95% CI=[${lower}, ${upper}]`);
```
### `histogram.min`
<!-- YAML
+24
View File
@@ -197,6 +197,30 @@ class Histogram {
return this[kHandle]?.mean();
}
/**
* Returns a confidence interval for the mean using Student's t-distribution.
* @param {{ confidence?: number }} [options]
* @returns {{ mean: number, lower: number, upper: number }}
*/
meanCI(options = kEmptyObject) {
if (!isHistogram(this))
throw new ERR_INVALID_THIS('Histogram');
validateObject(options, 'options');
const { confidence = 0.95 } = options;
validateNumber(confidence, 'options.confidence');
if (NumberIsNaN(confidence) || confidence <= 0 || confidence >= 1)
throw new ERR_OUT_OF_RANGE('options.confidence',
'> 0 && < 1', confidence);
const result = this[kHandle]?.meanCI(confidence);
if (result === undefined) return undefined;
return {
__proto__: null,
mean: result[0],
lower: result[1],
upper: result[2],
};
}
/**
* @readonly
* @type {number}
+59 -17
View File
@@ -298,28 +298,29 @@ static double NormalCdf(double x) {
// Student's t-distribution CDF: P(T <= t) for df degrees of freedom.
static double StudentTCdf(double t, double df) {
double x = df / (df + t * t);
double ibeta = RegularizedIncompleteBeta(df / 2.0, 0.5, x);
if (t >= 0.0) {
return 1.0 - 0.5 * ibeta;
double squared = t * t;
double denominator = df + squared;
if (squared < df) {
double x = squared / denominator;
double ibeta = RegularizedIncompleteBeta(0.5, df / 2.0, x);
return t >= 0.0 ? 0.5 + 0.5 * ibeta : 0.5 - 0.5 * ibeta;
}
return 0.5 * ibeta;
double x = df / denominator;
double ibeta = RegularizedIncompleteBeta(df / 2.0, 0.5, x);
return t >= 0.0 ? 1.0 - 0.5 * ibeta : 0.5 * ibeta;
}
// Student's t-distribution quantile (inverse CDF) using bisection.
// Returns the value t such that P(T <= t) = p.
static double StudentTQuantile(double p, double df) {
if (p <= 0.0) return -std::numeric_limits<double>::infinity();
if (p >= 1.0) return std::numeric_limits<double>::infinity();
if (p == 0.5) return 0.0;
// Positive Student's t-distribution quantile for an upper-tail probability.
// Using the lower tail avoids loss of precision for probabilities near 1.
static double StudentTUpperQuantile(double p, double df) {
double lo = 0.0;
double hi = 1.0;
while (StudentTCdf(-hi, df) > p) hi *= 2.0;
// Bisection search. The range [-1e6, 1e6] is sufficient for any
// practical confidence level and degrees of freedom.
double lo = -1e6;
double hi = 1e6;
for (int i = 0; i < 100; i++) {
double mid = (lo + hi) / 2.0;
if (StudentTCdf(mid, df) < p) {
if (StudentTCdf(-mid, df) > p) {
lo = mid;
} else {
hi = mid;
@@ -482,6 +483,30 @@ constexpr uint64_t kEwmaErrorRate = 3;
constexpr uint64_t kEwmaThreshold = 4;
} // namespace
Histogram::MeanCIResult Histogram::MeanCI(double confidence) const {
RwLock::ScopedReadLock lock(mutex_);
int64_t count = histogram_->total_count;
double mean = hdr_mean(histogram_.get());
if (count < 2) {
double nan = std::numeric_limits<double>::quiet_NaN();
return {mean, nan, nan};
}
double stddev = hdr_stddev(histogram_.get());
if (stddev == 0.0) return {mean, mean, mean};
// HdrHistogram computes population stddev (divides by N). The confidence
// interval requires sample variance (divides by N-1).
double variance = stddev * stddev * static_cast<double>(count) /
static_cast<double>(count - 1);
double standard_error = std::sqrt(variance / static_cast<double>(count));
double alpha = 1.0 - confidence;
double t_crit = StudentTUpperQuantile(
alpha / 2.0, static_cast<double>(count - 1));
double margin = t_crit * standard_error;
return {mean, mean - margin, mean + margin};
}
Histogram::WelchTestResult Histogram::WelchTest(const Histogram& other,
double confidence) const {
auto do_welch = [&]() -> WelchTestResult {
@@ -517,7 +542,7 @@ Histogram::WelchTestResult Histogram::WelchTest(const Histogram& other,
// Confidence interval on the difference of means.
double alpha = 1.0 - confidence;
double t_crit = StudentTQuantile(1.0 - alpha / 2.0, df);
double t_crit = StudentTUpperQuantile(alpha / 2.0, df);
double margin = t_crit * std::sqrt(se_sum);
double diff = mean1 - mean2;
@@ -1133,6 +1158,7 @@ void HistogramImpl::AddMethods(Isolate* isolate, Local<FunctionTemplate> tmpl) {
SetProtoMethodNoSideEffect(isolate, tmpl, "percentilesAt", GetPercentilesAt);
SetProtoMethodNoSideEffect(isolate, tmpl, "linearBuckets", GetLinearBuckets);
SetProtoMethodNoSideEffect(isolate, tmpl, "logBuckets", GetLogBuckets);
SetProtoMethodNoSideEffect(isolate, tmpl, "meanCI", GetMeanCI);
SetProtoMethodNoSideEffect(isolate, tmpl, "welchTest", GetWelchTest);
SetProtoMethodNoSideEffect(
isolate, tmpl, "mannWhitneyTest", GetMannWhitneyTest);
@@ -1187,6 +1213,7 @@ void HistogramImpl::RegisterExternalReferences(
registry->Register(GetPercentilesAt);
registry->Register(GetLinearBuckets);
registry->Register(GetLogBuckets);
registry->Register(GetMeanCI);
registry->Register(GetWelchTest);
registry->Register(GetMannWhitneyTest);
registry->Register(GetCohensD);
@@ -1895,6 +1922,21 @@ void HistogramImpl::GetKsTest(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set((*histogram)->KsTest(*(other->histogram())));
}
void HistogramImpl::GetMeanCI(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
HistogramImpl* histogram = HistogramImpl::FromJSObject(args.This());
CHECK(args[0]->IsNumber());
double confidence = args[0].As<Number>()->Value();
auto result = (*histogram)->MeanCI(confidence);
Local<Value> values[] = {Number::New(isolate, result.mean),
Number::New(isolate, result.lower),
Number::New(isolate, result.upper)};
Local<Array> arr = Array::New(isolate, &values[0], arraysize(values));
args.GetReturnValue().Set(arr);
}
void HistogramImpl::GetWelchTest(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
HistogramImpl* histogram = HistogramImpl::FromJSObject(args.This());
+9 -1
View File
@@ -80,7 +80,13 @@ class Histogram : public MemoryRetainer {
int64_t* values,
size_t length) const;
// Statistical hypothesis testing
// Statistical analysis
struct MeanCIResult {
double mean;
double lower;
double upper;
};
struct WelchTestResult {
double t_statistic;
double degrees_of_freedom;
@@ -101,6 +107,7 @@ class Histogram : public MemoryRetainer {
int64_t upper;
};
MeanCIResult MeanCI(double confidence = 0.95) const;
WelchTestResult WelchTest(const Histogram& other,
double confidence = 0.95) const;
MannWhitneyResult MannWhitneyTest(const Histogram& other) const;
@@ -189,6 +196,7 @@ class HistogramImpl {
static void GetPercentilesAt(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetLinearBuckets(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetLogBuckets(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetMeanCI(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetWelchTest(const v8::FunctionCallbackInfo<v8::Value>& args);
static void GetMannWhitneyTest(
const v8::FunctionCallbackInfo<v8::Value>& args);
@@ -5,6 +5,85 @@ require('../common');
const assert = require('assert');
const { createHistogram, importHistogram } = require('perf_hooks');
// ---------------------------------------------------------------------------
// meanCI([options]) — confidence interval for the mean
// ---------------------------------------------------------------------------
{
const empty = createHistogram();
const emptyCI = empty.meanCI();
assert.strictEqual(Object.getPrototypeOf(emptyCI), null);
assert.ok(Number.isNaN(emptyCI.mean));
assert.ok(Number.isNaN(emptyCI.lower));
assert.ok(Number.isNaN(emptyCI.upper));
// A confidence interval is undefined with fewer than two samples.
const one = createHistogram();
one.record(42);
const oneCI = one.meanCI();
assert.strictEqual(oneCI.mean, 42);
assert.ok(Number.isNaN(oneCI.lower));
assert.ok(Number.isNaN(oneCI.upper));
// This known sample has a 95% Student's t confidence interval of
// approximately [3.334149, 7.665851].
const h = createHistogram();
for (let i = 1; i <= 10; i++) h.record(i);
const ci95 = h.meanCI();
assert.strictEqual(ci95.mean, h.mean);
assert.ok(Math.abs(ci95.lower - 3.3341494103866087) < 1e-6);
assert.ok(Math.abs(ci95.upper - 7.665850589613392) < 1e-6);
// Higher confidence produces a wider interval.
const ci90 = h.meanCI({ confidence: 0.90 });
const ci99 = h.meanCI({ confidence: 0.99 });
assert.ok((ci99.upper - ci99.lower) > (ci90.upper - ci90.lower));
// Very low confidence levels retain precision near the center of the
// distribution. With two samples, the t-distribution has one degree of
// freedom and the expected interval width is tan(pi * confidence / 2).
const two = createHistogram();
two.record(1);
two.record(2);
const lowConfidence = 1e-9;
const narrowCI = two.meanCI({ confidence: lowConfidence });
const expectedWidth = Math.tan(Math.PI * lowConfidence / 2);
const actualWidth = narrowCI.upper - narrowCI.lower;
assert.ok(Math.abs(actualWidth - expectedWidth) / expectedWidth < 1e-4);
// Very high confidence levels are not truncated by the quantile search.
const extremeCI = two.meanCI({ confidence: 0.9999999 });
assert.ok(extremeCI.lower < -3_000_000);
assert.ok(extremeCI.upper > 3_000_000);
const highestCI = two.meanCI({
confidence: 1 - Number.EPSILON / 2,
});
assert.ok(Number.isFinite(highestCI.lower));
assert.ok(Number.isFinite(highestCI.upper));
// Constant values have no sampling uncertainty.
const constant = createHistogram();
for (let i = 0; i < 100; i++) constant.record(7);
assert.deepStrictEqual(constant.meanCI(), {
__proto__: null,
mean: 7,
lower: 7,
upper: 7,
});
// Validation.
assert.throws(() => h.meanCI({ confidence: 0 }),
{ code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => h.meanCI({ confidence: 1 }),
{ code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => h.meanCI({ confidence: NaN }),
{ code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => h.meanCI({ confidence: 'high' }),
{ code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => h.meanCI(null),
{ code: 'ERR_INVALID_ARG_TYPE' });
}
// ---------------------------------------------------------------------------
// welchTest(other) — Welch's t-test
// ---------------------------------------------------------------------------
@@ -586,6 +665,7 @@ const { createHistogram, importHistogram } = require('perf_hooks');
const wrongThis = {};
const methods = [
['meanCI', []],
['welchTest', [h]],
['mannWhitneyTest', [h]],
['cohensD', [h]],
@@ -633,6 +713,7 @@ const { createHistogram, importHistogram } = require('perf_hooks');
stub[kHandle] = null;
assert.strictEqual(stub.welchTest(h), undefined);
assert.strictEqual(stub.meanCI(), undefined);
assert.strictEqual(stub.mannWhitneyTest(h), undefined);
assert.strictEqual(stub.percentileCI(50), undefined);
assert.strictEqual(stub.burnRate(0.999), undefined);