-
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
-
36
-
37
-
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
-
54
-
55
-
56
-
57
-
58
-
59
-
60
-
61
-
62
-
63
-
64
-
65
-
66
-
67
-
68
-
69
-
70
-
71
-
72
-
73
-
74
-
75
-
76
-
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
-
87
-
88
-
89
-
90
-
91
-
92
-
93
-
94
-
95
-
96
-
97
-
98
-
99
-
100
-
101
-
102
-
103
-
104
-
105
class Group {
/**
* @param name {string}
* @param bench {readonly Bench[]}
* @param samples {number}
*/
constructor(name, bench, samples = 10_000) {
/**
* @type {string}
* @public
*/
this.name = name;
/**
* @type {readonly Bench[]}
* @public
*/
this.bench = bench;
/**
* @type {number}
* @public
*/
this.samples = samples;
}
async run() {
const { samples } = this;
console.group(`${this.name} (n=${samples})`);
for (const bench of this.bench) {
const ds = [];
for (let i = 0; i < samples; i++) {
ds.push(await bench.run());
}
const ordered = ds.sort((a, b) => a - b);
const total = ds.reduce((a, b) => a + b, 0);
console.group(bench.name);
console.log("total: ", total);
console.log("avg: ", total / samples);
console.log("p75: ", ordered[(ordered.length * 0.75) | 0]);
console.log("p90: ", ordered[(ordered.length * 0.9) | 0]);
console.groupEnd();
}
console.groupEnd();
}
}
/**
* @param name {string}
* @param benches {readonly Bench[]}
*/
export function group(name, benches) {
return new Group(name, benches);
}
class Bench {
/**
* @param name {string}
* @param f {() => (void | Promise<void>)}
*/
constructor(name, f) {
/**
* @type {string}
* @public
*/
this.name = name;
/**
* @type {() => (void | Promise<void>)}
* @private
*/
this.f = f;
}
/**
* @returns {number | Promise<number>}
*/
run() {
const start = performance.now();
const ret = this.f();
if (ret instanceof Promise) {
return ret.then(() => {
return performance.now() - start;
});
}
return performance.now() - start;
}
}
/**
* @param name {string}
* @param f {() => (void | Promise<void>)}
*/
export function bench(name, f) {
return new Bench(name, f);
}