-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbench.js
60 lines (48 loc) · 1.18 KB
/
bench.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
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
'use strict'
function bench () {
const results = []
let timeTaken = 0
let runnerStarted = 0
let runnerTook = 0
let running = false
function formatResults () {
return results
}
async function benchmark (f, timeLimit) {
running = true
const runner = async function () {
const start = Date.now()
await f()
results.push(Date.now() - start)
}
const benchStart = Date.now()
do {
runnerStarted = Date.now()
await runner()
runnerTook = Date.now() - runnerStarted
timeTaken += runnerTook
if (timeTaken >= (timeLimit -
Math.ceil(results.reduce((accumulator, current) => accumulator + current, 0) / results.length))) {
running = false
break
}
} while (running)
return {
results: formatResults(),
min: Math.min(...results),
max: Math.max(...results),
average: Math.ceil(results.reduce((accumulator, current) => accumulator + current, 0) / results.length),
runs: results.length,
timeLimit,
timeTaken,
benchTime: Date.now() - benchStart
}
}
return {
benchmark
}
}
const benchmark = bench().benchmark
export {
benchmark
}