Skip to content

Commit d15f18b

Browse files
jasnelladuh95
authored andcommitted
lib: update node:bench reporters to include sys info
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode PR-URL: #66664 Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent c15d48a commit d15f18b

6 files changed

Lines changed: 202 additions & 17 deletions

File tree

‎doc/api/bench.md‎

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -260,13 +260,36 @@ bench('example', (b) => {
260260
run().compose(spec).pipe(process.stdout);
261261
```
262262

263-
The `spec` reporter buffers results and outputs a concise table containing the
264-
sample count, mean rate, 95% confidence interval for the mean, median rate, and
265-
warnings. A coefficient of variation above 5% is reported as `noisy`, and an
266-
absolute skewness above 1 is reported as `skewed`. The exact human-readable
267-
format is subject to change.
268-
269-
The `json` reporter emits every lifecycle record as newline-delimited JSON.
263+
The built-in reporters collect a snapshot of the reporting process's
264+
environment when they receive their first record. The snapshot contains:
265+
266+
* `node` {string} The value of `process.version`.
267+
* `v8` {string} The value of `process.versions.v8`.
268+
* `platform` {string} The value of `process.platform`.
269+
* `arch` {string} The value of `process.arch`.
270+
* `os` {Object} The operating system `type`, `release`, and `machine`, as
271+
returned by the corresponding [`os`][] functions.
272+
* `cpus` {Object\[]} The logical CPUs grouped by `model`, with the `count` of
273+
each model.
274+
* `availableParallelism` {number} The value of `os.availableParallelism()`.
275+
* `memory` {Object} The `total` and `free` system memory in bytes, and the
276+
`constrained` memory limit in bytes, or `null` when the process is not
277+
constrained below the total system memory.
278+
* `loadavg` {number\[]} The value of `os.loadavg()`.
279+
* `execArgv` {string\[]} The value of `process.execArgv`.
280+
281+
With process isolation, reporters run in the parent process. Benchmark children
282+
are started from the same executable, but their `execArgv` can differ.
283+
284+
The `spec` reporter buffers results and outputs a summary of the environment
285+
followed by a concise table containing the sample count, mean rate, 95%
286+
confidence interval for the mean, median rate, and warnings. A coefficient of
287+
variation above 5% is reported as `noisy`, and an absolute skewness above 1 is
288+
reported as `skewed`. The exact human-readable format is subject to change.
289+
290+
The `json` reporter emits a `'bench:environment'` record containing the
291+
environment snapshot before the first lifecycle record, and then emits every
292+
lifecycle record as newline-delimited JSON.
270293
BigInt values, including `duration_ns`, are encoded as decimal strings. Errors
271294
are represented using their `name`, `message`, `stack`, `code`, `cause`, and
272295
`errors` properties. As required by JSON, non-finite numbers are encoded as
@@ -798,7 +821,8 @@ tags, and parameters described in [benchmark result][], together with:
798821

799822
The plan contains execution settings known to the runner. Runtime version,
800823
operating system, processor, and other environment metadata are intentionally
801-
left for reporters and higher-level tools to collect.
824+
left for reporters and higher-level tools to collect. The built-in reporters
825+
include an [environment snapshot][benchmark reporters].
802826

803827
`'bench:complete'` data contains a [benchmark result][]. A failed result has an
804828
additional `error` property and may contain samples recorded before the error.
@@ -856,6 +880,8 @@ A completed benchmark result contains:
856880

857881
[`context.record()`]: #contextrecordsample
858882
[`createRunner()`]: #createrunneroptions
883+
[`os`]: os.md
859884
[`run()`]: #runoptions
885+
[benchmark reporters]: #benchmark-reporters
860886
[benchmark result]: #benchmark-result
861887
[command-line options documentation]: cli.md#--bench
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
'use strict';
2+
3+
const {
4+
ArrayPrototypePush,
5+
ArrayPrototypeSlice,
6+
} = primordials;
7+
8+
function groupCpus(cpus) {
9+
const groups = [];
10+
for (let i = 0; i < cpus.length; i++) {
11+
// The reported speed is the current core frequency, which fluctuates
12+
// with frequency scaling, so only the model is used for grouping.
13+
const { model } = cpus[i];
14+
let group;
15+
for (let j = 0; j < groups.length; j++) {
16+
if (groups[j].model === model) {
17+
group = groups[j];
18+
break;
19+
}
20+
}
21+
if (group === undefined) {
22+
group = { __proto__: null, model, count: 0 };
23+
ArrayPrototypePush(groups, group);
24+
}
25+
group.count++;
26+
}
27+
return groups;
28+
}
29+
30+
function collectEnvironment() {
31+
const os = require('os');
32+
const total = os.totalmem();
33+
const constrained = process.constrainedMemory();
34+
return {
35+
__proto__: null,
36+
node: process.version,
37+
v8: process.versions.v8,
38+
platform: process.platform,
39+
arch: process.arch,
40+
os: {
41+
__proto__: null,
42+
type: os.type(),
43+
release: os.release(),
44+
machine: os.machine(),
45+
},
46+
cpus: groupCpus(os.cpus()),
47+
availableParallelism: os.availableParallelism(),
48+
memory: {
49+
__proto__: null,
50+
total,
51+
free: os.freemem(),
52+
constrained: constrained > 0 && constrained < total ? constrained : null,
53+
},
54+
loadavg: os.loadavg(),
55+
execArgv: ArrayPrototypeSlice(process.execArgv),
56+
};
57+
}
58+
59+
module.exports = {
60+
collectEnvironment,
61+
};

‎lib/internal/bench_runner/reporter/json.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ const {
99
String,
1010
} = primordials;
1111
const { isError } = require('internal/util');
12+
const {
13+
collectEnvironment,
14+
} = require('internal/bench_runner/environment');
1215

1316
function toJSONValue(value, seen) {
1417
if (typeof value === 'bigint') return String(value);
@@ -56,7 +59,16 @@ function stringify(record) {
5659
}
5760

5861
async function* jsonReporter(source) {
62+
let environmentReported = false;
5963
for await (const record of source) {
64+
if (!environmentReported) {
65+
environmentReported = true;
66+
yield `${stringify({
67+
__proto__: null,
68+
type: 'bench:environment',
69+
data: collectEnvironment(),
70+
})}\n`;
71+
}
6072
yield `${stringify(record)}\n`;
6173
}
6274
}

‎lib/internal/bench_runner/reporter/spec.js‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ const {
1313
StringPrototypeReplaceAll,
1414
} = primordials;
1515
const Transform = require('internal/streams/transform');
16+
const {
17+
collectEnvironment,
18+
} = require('internal/bench_runner/environment');
1619

1720
const kHeader =
1821
'benchmark | samples | mean rate | 95% CI | median rate | warning\n';
@@ -62,6 +65,50 @@ function formatRate(rate) {
6265
return `${formatted}${prefix} ops/s`;
6366
}
6467

68+
function formatBytes(bytes) {
69+
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
70+
let unit = 0;
71+
while (bytes >= 1024 && unit < units.length - 1) {
72+
bytes /= 1024;
73+
unit++;
74+
}
75+
return `${NumberPrototypeToFixed(bytes, unit === 0 ? 0 : 1)} ${units[unit]}`;
76+
}
77+
78+
function formatEnvironment(environment) {
79+
const { cpus, memory, os } = environment;
80+
let output = `node: ${environment.node} (V8 ${environment.v8}), ` +
81+
`${environment.platform} ${environment.arch} ` +
82+
`(${os.type} ${os.release})\n`;
83+
84+
const groups = [];
85+
for (let i = 0; i < cpus.length; i++) {
86+
ArrayPrototypePush(groups, `${cpus[i].count} x ${cpus[i].model}`);
87+
}
88+
if (groups.length === 0) ArrayPrototypePush(groups, 'unknown');
89+
output += `cpu: ${ArrayPrototypeJoin(groups, ', ')} ` +
90+
`(available parallelism: ${environment.availableParallelism})\n`;
91+
92+
output += `memory: ${formatBytes(memory.total)} total, ` +
93+
`${formatBytes(memory.free)} free`;
94+
if (memory.constrained !== null) {
95+
output += `, ${formatBytes(memory.constrained)} constrained`;
96+
}
97+
output += '\n';
98+
99+
const loadavg = [];
100+
for (let i = 0; i < environment.loadavg.length; i++) {
101+
ArrayPrototypePush(
102+
loadavg, NumberPrototypeToFixed(environment.loadavg[i], 2));
103+
}
104+
output += `load average: ${ArrayPrototypeJoin(loadavg, ', ')}\n`;
105+
106+
if (environment.execArgv.length > 0) {
107+
output += `exec argv: ${ArrayPrototypeJoin(environment.execArgv, ' ')}\n`;
108+
}
109+
return `${output}\n`;
110+
}
111+
65112
function formatWarning(summary) {
66113
const warnings = [];
67114
if (NumberIsFinite(summary.coefficientOfVariation) &&
@@ -97,6 +144,7 @@ function formatResult(data) {
97144

98145
class SpecReporter extends Transform {
99146
#diagnostics = [];
147+
#environment;
100148
#reported = false;
101149
#results = [];
102150

@@ -105,7 +153,7 @@ class SpecReporter extends Transform {
105153
}
106154

107155
#format(summary = undefined) {
108-
let output = kHeader;
156+
let output = formatEnvironment(this.#environment) + kHeader;
109157
for (let i = 0; i < this.#results.length; i++) {
110158
output += formatResult(this.#results[i]);
111159
}
@@ -121,6 +169,7 @@ class SpecReporter extends Transform {
121169
}
122170

123171
_transform({ type, data }, _encoding, callback) {
172+
this.#environment ??= collectEnvironment();
124173
switch (type) {
125174
case 'bench:complete':
126175
ArrayPrototypePush(this.#results, data);

‎test/parallel/test-bench-cli-reporters.js‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,16 +125,19 @@ for (const { file, status } of [
125125
fixtures.path('bench-runner/a.cjs'),
126126
]);
127127
assert.strictEqual(result.status, 0);
128-
parseRecords(result);
129-
assert.match(fs.readFileSync(destination, 'utf8'),
130-
/^benchmark \| samples \| mean rate/);
128+
const records = parseRecords(result);
129+
assert.strictEqual(records[0].type, 'bench:environment');
130+
const output = fs.readFileSync(destination, 'utf8');
131+
assert.match(output, /^node: v\d+/);
132+
assert.match(output, /^benchmark \| samples \| mean rate/m);
131133
}
132134

133135
{
134136
const result = spawnBench([fixtures.path('bench-runner/a.cjs')]);
135137
assert.strictEqual(result.status, 0);
136138
assert.strictEqual(result.stderr, '');
137-
assert.match(result.stdout, /^benchmark \| samples \| mean rate/);
139+
assert.match(result.stdout, /^node: v\d+/);
140+
assert.match(result.stdout, /^benchmark \| samples \| mean rate/m);
138141
assert.match(result.stdout, /1 completed, 0 failed, 0 skipped/);
139142
}
140143

‎test/parallel/test-bench-reporters.js‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
const common = require('../common');
55
const { completeSample } = require('../common/bench');
66
const assert = require('assert');
7+
const os = require('os');
78
const { Readable } = require('stream');
89
const { bench, run } = require('node:bench');
910
const { json, spec } = require('node:bench/reporters');
@@ -26,7 +27,25 @@ bench('json failed', { samples: 1 }, () => {
2627
const lines = chunks.join('').trim().split('\n');
2728
const records = lines.map((line) => JSON.parse(line));
2829

29-
assert.strictEqual(records.length, 8);
30+
assert.strictEqual(records.length, 9);
31+
const { type: environmentType, data: environment } = records[0];
32+
assert.strictEqual(environmentType, 'bench:environment');
33+
assert.strictEqual(environment.node, process.version);
34+
assert.strictEqual(environment.v8, process.versions.v8);
35+
assert.strictEqual(environment.platform, process.platform);
36+
assert.strictEqual(environment.arch, process.arch);
37+
assert.strictEqual(environment.os.type, os.type());
38+
assert.strictEqual(environment.os.release, os.release());
39+
assert.strictEqual(environment.os.machine, os.machine());
40+
assert.strictEqual(
41+
environment.cpus.reduce((total, { count }) => total + count, 0),
42+
os.cpus().length);
43+
assert.strictEqual(environment.availableParallelism,
44+
os.availableParallelism());
45+
assert.strictEqual(environment.memory.total, os.totalmem());
46+
assert.strictEqual(typeof environment.memory.free, 'number');
47+
assert.strictEqual(environment.loadavg.length, 3);
48+
assert.deepStrictEqual(environment.execArgv, process.execArgv);
3049
const plans = records.filter(({ type }) => type === 'bench:plan');
3150
assert.deepStrictEqual(plans.map(({ data }) => data.selected), [true, true]);
3251
const sample = records.find(({ type }) => type === 'bench:sample');
@@ -105,7 +124,18 @@ bench('json failed', { samples: 1 }, () => {
105124
},
106125
];
107126
const specChunks = await Readable.from(synthetic).compose(spec).toArray();
108-
assert.strictEqual(specChunks.join(''),
127+
const specOutput = specChunks.join('');
128+
const specHeaderEnd = specOutput.indexOf('\n\n') + 2;
129+
const specHeader = specOutput.slice(0, specHeaderEnd);
130+
assert.match(specHeader,
131+
new RegExp(`^node: ${RegExp.escape(process.version)} ` +
132+
`\\(V8 ${RegExp.escape(process.versions.v8)}\\), ` +
133+
`${process.platform} ${process.arch} `));
134+
assert.match(specHeader, /^cpu: .*\(available parallelism: \d+\)$/m);
135+
assert.match(specHeader, /^memory: [\d.]+ \w+ total, [\d.]+ \w+ free/m);
136+
assert.match(specHeader, /^load average: [\d.]+, [\d.]+, [\d.]+$/m);
137+
assert.match(specHeader, /^exec argv: --experimental-bench --no-warnings$/m);
138+
assert.strictEqual(specOutput.slice(specHeaderEnd),
109139
'benchmark | samples | mean rate | 95% CI | ' +
110140
'median rate | warning\n' +
111141
'fast [size="small"] | 2 | 1.50k ops/s | ' +
@@ -123,7 +153,8 @@ bench('json failed', { samples: 1 }, () => {
123153
type: 'bench:diagnostic',
124154
data: { aggregate, circular },
125155
}]).compose(json).toArray();
126-
const jsonEdge = JSON.parse(jsonEdgeChunks.join(''));
156+
assert.strictEqual(jsonEdgeChunks.length, 2);
157+
const jsonEdge = JSON.parse(jsonEdgeChunks[1]);
127158
assert.deepStrictEqual(jsonEdge.data.aggregate.errors, ['1']);
128159
assert.strictEqual(jsonEdge.data.circular.self, '[Circular]');
129160

@@ -134,7 +165,10 @@ bench('json failed', { samples: 1 }, () => {
134165
for await (const chunk of json(undefinedRecord())) {
135166
undefinedChunks.push(chunk);
136167
}
137-
assert.strictEqual(undefinedChunks.join(''), 'null\n');
168+
assert.strictEqual(undefinedChunks.length, 2);
169+
assert.strictEqual(JSON.parse(undefinedChunks[0]).type,
170+
'bench:environment');
171+
assert.strictEqual(undefinedChunks[1], 'null\n');
138172

139173
function result(name, rate) {
140174
return {

0 commit comments

Comments
 (0)