Skip to content

Commit 9e4c1f2

Browse files
aduh95targos
authored andcommitted
benchmark: use process.hrtime.bigint()
PR-URL: #38369 Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent cede0c5 commit 9e4c1f2

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

benchmark/common.js

+21-9
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ class Benchmark {
1212
this._ended = false;
1313

1414
// Holds process.hrtime value
15-
this._time = [0, 0];
15+
this._time = 0n;
1616

1717
// Use the file name as the name of the benchmark
1818
this.name = require.main.filename.slice(__dirname.length + 1);
@@ -218,12 +218,12 @@ class Benchmark {
218218
throw new Error('Called start more than once in a single benchmark');
219219
}
220220
this._started = true;
221-
this._time = process.hrtime();
221+
this._time = process.hrtime.bigint();
222222
}
223223

224224
end(operations) {
225225
// Get elapsed time now and do error checking later for accuracy.
226-
const elapsed = process.hrtime(this._time);
226+
const time = process.hrtime.bigint();
227227

228228
if (!this._started) {
229229
throw new Error('called end without start');
@@ -237,16 +237,19 @@ class Benchmark {
237237
if (!process.env.NODEJS_BENCHMARK_ZERO_ALLOWED && operations <= 0) {
238238
throw new Error('called end() with operation count <= 0');
239239
}
240-
if (elapsed[0] === 0 && elapsed[1] === 0) {
240+
241+
this._ended = true;
242+
243+
if (time === this._time) {
241244
if (!process.env.NODEJS_BENCHMARK_ZERO_ALLOWED)
242245
throw new Error('insufficient clock precision for short benchmark');
243246
// Avoid dividing by zero
244-
elapsed[1] = 1;
247+
this.report(operations && Number.MAX_VALUE, 0n);
248+
return;
245249
}
246250

247-
this._ended = true;
248-
const time = elapsed[0] + elapsed[1] / 1e9;
249-
const rate = operations / time;
251+
const elapsed = time - this._time;
252+
const rate = operations / (Number(elapsed) / 1e9);
250253
this.report(rate, elapsed);
251254
}
252255

@@ -255,12 +258,21 @@ class Benchmark {
255258
name: this.name,
256259
conf: this.config,
257260
rate,
258-
time: elapsed[0] + elapsed[1] / 1e9,
261+
time: nanoSecondsToString(elapsed),
259262
type: 'report',
260263
});
261264
}
262265
}
263266

267+
function nanoSecondsToString(bigint) {
268+
const str = bigint.toString();
269+
const decimalPointIndex = str.length - 9;
270+
if (decimalPointIndex < 0) {
271+
return `0.${'0'.repeat(-decimalPointIndex)}${str}`;
272+
}
273+
return `${str.slice(0, decimalPointIndex)}.${str.slice(decimalPointIndex)}`;
274+
}
275+
264276
function formatResult(data) {
265277
// Construct configuration string, " A=a, B=b, ..."
266278
let conf = '';

0 commit comments

Comments
 (0)