-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
runner.js
180 lines (150 loc) · 4.62 KB
/
runner.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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
'use strict';
const CONSTANTS = require('./constants');
const { performance } = require('perf_hooks');
const Suite = require('./suite');
const PERCENTILES = [10, 25, 50, 75, 95, 98, 99];
function percentileIndex(percentile, total) {
return Math.max(Math.floor((total * percentile) / 100 - 1), 0);
}
async function timeTask(task, ctx) {
const start = performance.now();
await task.call(ctx);
const end = performance.now();
return (end - start) / 1000;
}
/**
* Returns the execution time for the benchmarks in mb/second
*
* This function internally calculates the 50th percentile execution time and uses
* that as the median.
*
* @param {Benchmark} benchmark
* @param {{ rawData: number[], count: number}} data
* @returns number
*/
function calculateMicroBench(benchmark, data) {
const rawData = data.rawData;
const count = data.count;
const sortedData = [].concat(rawData).sort();
const percentiles = PERCENTILES.reduce((acc, pct) => {
acc[pct] = sortedData[percentileIndex(pct, count)];
return acc;
}, {});
const medianExecution = percentiles[50];
return benchmark.taskSize / medianExecution;
}
class Runner {
constructor(options) {
options = options || {};
this.minExecutionTime = options.minExecutionTime || CONSTANTS.DEFAULT_MIN_EXECUTION_TIME;
this.maxExecutionTime = options.maxExecutionTime || CONSTANTS.DEFAULT_MAX_EXECUTION_TIME;
this.minExecutionCount = options.minExecutionCount || CONSTANTS.DEFAULT_MIN_EXECUTION_COUNT;
this.reporter =
options.reporter ||
function () {
console.log.apply(console, arguments);
};
this.children = {};
}
/**
* Adds a new test suite to the runner
* @param {string} name - the name of the test suite
* @param {(suite: Suite) => void} fn a function that registers a set of benchmarks onto the
* parameter `suite`
* @returns {this} this
*/
suite(name, fn) {
if (typeof name !== 'string' || !name) {
throw new TypeError(`Argument "name" (${name}) must be a non-zero length string`);
}
if (typeof fn !== 'function') {
throw new TypeError(`Argument "fn" must be a function`);
}
if (name in this.children) {
throw new Error(`Name "${name}" already taken`);
}
const _suite = new Suite();
const suite = fn(_suite) || _suite;
if (!(suite instanceof Suite)) {
throw new TypeError(`returned object is not a suite`);
}
this.children[name] = suite;
return this;
}
async run() {
this.reporter(`Running Benchmarks`);
const result = {};
for (const [suiteName, suite] of Object.entries(this.children)) {
this.reporter(` Executing suite "${suiteName}"`);
result[suiteName] = await this._runSuite(suite);
}
return result;
}
/**
*
* @param {Suite} suite
*
* @returns {{string: number | undefined}}
*/
async _runSuite(suite) {
const benchmarks = Object.entries(suite.getBenchmarks()).map(([name, benchmark]) => [
name,
benchmark.toObj()
]);
const result = {};
for (const [name, benchmark] of benchmarks) {
this.reporter(` Executing Benchmark "${name}"`);
result[name] = await this._runBenchmark(benchmark);
}
return result;
}
/**
* Runs a single benchmark.
*
* @param {Benchmark} benchmark
* @returns {Promise<number>} A promise containing the mb/s for the benchmark. This function never rejects,
* it instead returns Promise<NaN> if there is an error.
*/
async _runBenchmark(benchmark) {
const ctx = {};
try {
await benchmark.setup.call(ctx);
const result = await this._loopTask(benchmark, ctx);
await benchmark.teardown.call(ctx);
return calculateMicroBench(benchmark, result);
} catch (error) {
return this._errorHandler(error);
}
}
/**
*
* @param {Benchmark} benchmark
* @param {any} ctx
* @returns {{ rawData: number[], count: number}}
*/
async _loopTask(benchmark, ctx) {
const start = performance.now();
const rawData = [];
const minExecutionCount = this.minExecutionCount;
const minExecutionTime = this.minExecutionTime;
const maxExecutionTime = this.maxExecutionTime;
let time = performance.now() - start;
let count = 1;
while (time < maxExecutionTime && (time < minExecutionTime || count < minExecutionCount)) {
await benchmark.beforeTask.call(ctx);
const executionTime = await timeTask(benchmark.task, ctx);
rawData.push(executionTime);
count++;
time = performance.now();
}
return {
rawData,
count
};
}
_errorHandler(e) {
console.error(e);
return NaN;
}
}
module.exports = Runner;