2020-11-30 22:05:19 +00:00
|
|
|
type PromiseOptional<T> = T | Promise<T>;
|
|
|
|
|
|
|
|
export async function runBenchmark<T, R>({
|
2020-11-13 23:09:13 +00:00
|
|
|
prepareTest,
|
|
|
|
testRunner,
|
|
|
|
runs = 100,
|
|
|
|
id,
|
|
|
|
}: {
|
2021-04-05 19:00:49 +00:00
|
|
|
prepareTest: (i: number) => PromiseOptional<T>;
|
2020-11-30 22:05:19 +00:00
|
|
|
testRunner: (input: T) => PromiseOptional<R>;
|
2020-11-13 23:09:13 +00:00
|
|
|
runs?: number;
|
|
|
|
id: string;
|
2020-11-30 22:05:19 +00:00
|
|
|
}): Promise<void> {
|
2020-11-13 23:09:13 +00:00
|
|
|
const diffsNanoSec: bigint[] = [];
|
|
|
|
|
|
|
|
for (let i = 0; i < runs; i++) {
|
2021-04-05 19:00:49 +00:00
|
|
|
const input = await prepareTest(i);
|
2020-11-13 23:09:13 +00:00
|
|
|
|
|
|
|
const start = process.hrtime.bigint();
|
2020-11-30 22:05:19 +00:00
|
|
|
const result = await testRunner(input);
|
2020-11-13 23:09:13 +00:00
|
|
|
const end = process.hrtime.bigint();
|
|
|
|
|
|
|
|
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);
|
|
|
|
}
|