-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathbenchmark.js
More file actions
33 lines (26 loc) · 801 Bytes
/
benchmark.js
File metadata and controls
33 lines (26 loc) · 801 Bytes
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
/*
* benchmark - benchmark a piece of code and return some stats about it
* fn: the function to benchmark
* opts: {iterations,timeout}
*/
function benchmark(fn,opts) {
var start = performance.now();
var end = start;
var times = [];
if(!(opts.iterations || opts.timeout)) return null;
var iterations = opts.iterations || Number.POSITIVE_INFINITY;
var timeout = opts.timeout || Number.POSITIVE_INFINITY;
var stop = start + timeout;
var i;
for(i = 0; i < iterations && end < stop; i++) {
var iterStart = performance.now();
fn();
end = performance.now();
times.push(end - iterStart);
}
var min = times.reduce(function (a,b) {return Math.min(a,b);});
var tot = end - start;
var avg = tot / i;
return {avg: avg, min: min, total: tot, iters: i};
}
module.exports = benchmark;