@jonahsnider/benchmark
Version:
A Node.js benchmarking library with support for multithreading and TurboFan optimization isolation.
54 lines • 2.02 kB
JavaScript
var _Test_implementation;
import { __classPrivateFieldGet, __classPrivateFieldSet } from "tslib";
import { createHistogram, performance } from 'node:perf_hooks';
/**
* Tracks a function's execution in {@link (Test:class).histogram}.
*
* @example
* ```ts
* import { Test } from '@jonahsnider/benchmark';
*
* const test = new Test(() => 'a' + 'b');
* ```
*
* @public
*/
export class Test {
/**
* Create a new {@link (Test:class)} with a given implementation.
*
* You probably don't want to instantiate this class directly, instead you can register tests with {@link (Suite:class).(addTest:2)}.
* You can also register {@link (Test:class)} instances with {@link (Suite:class).(addTest:1)}.
*
* @example
* ```ts
* const test = new Test(() => 'a' + 'b');
* ```
*
* @param implementation - The implementation function of the test
*/
constructor(implementation) {
/** Execution times for this {@link (Test:class)}'s implementation. */
this.histogram = createHistogram();
_Test_implementation.set(this, void 0);
__classPrivateFieldSet(this, _Test_implementation, () => {
const startMs = performance.now();
const result = implementation();
const endMs = performance.now();
const durationNs = Math.round((endMs - startMs) * 1e6);
// Sometimes the duration is 0, seems like it's only when running on arm64 - see https://github.com/nodejs/node/issues/41641
this.histogram.record(durationNs || 1);
return result;
}, "f");
}
/**
* Runs this {@link (Test:class)}'s implementation once and records the execution time in {@link (Test:class).histogram}.
*
* @returns The return value of this {@link (Test:class)}'s implementation
*/
async run() {
return __classPrivateFieldGet(this, _Test_implementation, "f").call(this);
}
}
_Test_implementation = new WeakMap();
//# sourceMappingURL=test.js.map