This repository has been archived on 2023-04-09. You can view files and clone it, but cannot push or open issues or pull requests.
2020-11-13 23:09:13 +00:00
|
|
|
export function runBenchmark<T, R>({
|
|
|
|
prepareTest,
|
|
|
|
testRunner,
|
|
|
|
runs = 100,
|
|
|
|
id,
|
|
|
|
}: {
|
|
|
|
prepareTest: (i: number) => {input: T; resultCheck?: (result: R) => boolean};
|
|
|
|
testRunner: (input: T) => R;
|
|
|
|
runs?: number;
|
|
|
|
id: string;
|
2020-11-20 12:27:30 +00:00
|
|
|
}): void {
|
2020-11-13 23:09:13 +00:00
|
|
|
const diffsNanoSec: bigint[] = [];
|
|
|
|
|
|
|
|
for (let i = 0; i < runs; i++) {
|
|
|
|
const {input, resultCheck} = prepareTest(i);
|
|
|
|
|
|
|
|
const start = process.hrtime.bigint();
|
|
|
|
const result = testRunner(input);
|
|
|
|
const end = process.hrtime.bigint();
|
|
|
|
|
|
|
|
if (resultCheck && !resultCheck(result)) throw Error("Result fails check test");
|
|
|
|
diffsNanoSec.push(end - start);
|
|
|
|
}
|
|
|
|
|
|
|
|
const average = averageBigint(diffsNanoSec);
|
|
|
|
const opsPerSec = 1e9 / Number(average);
|
2020-11-25 16:23:53 +00:00
|
|
|
// eslint-disable-next-line no-console
|
2020-11-13 23:09:13 +00:00
|
|
|
console.log(`${id}: ${opsPerSec.toPrecision(5)} ops/sec (${runs} runs)`); // ±1.74%
|
|
|
|
}
|
|
|
|
|
|
|
|
function averageBigint(arr: bigint[]): bigint {
|
|
|
|
const total = arr.reduce((total, value) => total + value);
|
|
|
|
return total / BigInt(arr.length);
|
|
|
|
}
|