-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbenchmark.js
35 lines (29 loc) · 1.25 KB
/
benchmark.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const benchmark = async ({ fn, params = [], targetTime, targetRuns, minRuns }) => {
if (typeof fn !== 'function') {
throw new TypeError('Can only benchmark a function');
}
if (!targetTime && !targetRuns) {
targetTime = 1;
}
if (!targetRuns) {
const startTime = process.hrtime.bigint();
await fn.call(null, ...params);
const endTime = process.hrtime.bigint();
const benchTime = Number(endTime - startTime);
targetRuns = Math.max(minRuns || 1, Number((1e9 * targetTime / Number(benchTime)).toPrecision(1)));
}
let totalTime = 0;
let batches = 0;
do {
for (let run = 1; run <= targetRuns; run += 1) {
const startTime = process.hrtime.bigint();
await fn.call(null, ...params);
const endTime = process.hrtime.bigint();
totalTime += Number(endTime - startTime);
}
batches += 1;
} while (targetTime && totalTime / 1e9 * (batches + 1) < targetTime * batches);
console.log(`Ran ${batches * targetRuns} times in ${batches} batches of ${targetRuns} runs each for a total time of ${totalTime / 1e9} out of ${targetTime}`);
return totalTime / 1e6 / (batches * targetRuns);
};
module.exports = { benchmark };