forked from rollup/rollup
/
perf.js
203 lines (188 loc) · 6.11 KB
/
perf.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/* global gc */
const fs = require('fs');
const path = require('path');
const colorette = require('colorette');
const prettyBytes = require('pretty-bytes');
const rollup = require('../dist/rollup.js');
const { loadPerfConfig, targetDir } = require('./load-perf-config');
const initialDir = process.cwd();
const perfFile = path.resolve(targetDir, 'rollup.perf.json');
let numberOfRunsToAverage = 6;
let numberOfDiscardedResults = 3;
if (process.argv.length >= 3) {
numberOfRunsToAverage = Number.parseInt(process.argv[2]);
if (process.argv.length >= 4) {
numberOfDiscardedResults = Number.parseInt(process.argv[3]);
}
}
if (!(numberOfDiscardedResults >= 0) || !(numberOfDiscardedResults < numberOfRunsToAverage)) {
console.error(
`Invalid parameters: runs = ${numberOfRunsToAverage}, discarded = ${numberOfDiscardedResults}.\n` +
'Usage: "npm run perf [<number of runs> [<number of discarded results>]]"\n' +
'where 0 <= <number of discarded results> < <number of runs>'
);
process.exit(1);
}
console.info(
colorette.bold(
`Calculating the average of ${colorette.cyan(
numberOfRunsToAverage
)} runs discarding the ${colorette.cyan(numberOfDiscardedResults)} largest results.\n`
) + 'Run "npm run perf <number of runs> <number of discarded results>" to change that.'
);
function getSingleAverage(times, runs, discarded) {
const actualDiscarded = Math.min(discarded, runs - 1);
return (
times
.sort()
.reverse()
.slice(actualDiscarded)
.reduce((sum, time) => sum + time, 0) /
(runs - actualDiscarded)
);
}
function getAverage(accumulatedMeasurements, runs, discarded) {
const average = {};
Object.keys(accumulatedMeasurements).forEach(label => {
average[label] = {
memory: getSingleAverage(
accumulatedMeasurements[label].map(timing => timing[2]),
runs,
discarded
),
time: getSingleAverage(
accumulatedMeasurements[label].map(timing => timing[0]),
runs,
discarded
)
};
});
return average;
}
async function calculatePrintAndPersistTimings(config, existingTimings) {
const timings = await buildAndGetTimings(config);
Object.keys(timings).forEach(label => {
timings[label] = [timings[label]];
});
for (let currentRun = 1; currentRun < numberOfRunsToAverage; currentRun++) {
const numberOfLinesToClear = printMeasurements(
getAverage(timings, currentRun, numberOfDiscardedResults),
existingTimings,
/^#/
);
console.info(`Completed run ${currentRun}.`);
const currentTimings = await buildAndGetTimings(config);
clearLines(numberOfLinesToClear);
Object.keys(timings).forEach(label => {
if (!currentTimings.hasOwnProperty(label)) {
delete timings[label];
} else {
timings[label].push(currentTimings[label]);
}
});
}
const averageTimings = getAverage(timings, numberOfRunsToAverage, numberOfDiscardedResults);
printMeasurements(averageTimings, existingTimings);
if (Object.keys(existingTimings).length === 0) persistTimings(averageTimings);
}
async function buildAndGetTimings(config) {
config.perf = true;
if (Array.isArray(config.output)) {
config.output = config.output[0];
}
gc();
process.chdir(targetDir);
const bundle = await rollup.rollup(config);
process.chdir(initialDir);
await bundle.generate(config.output);
return bundle.getTimings();
}
function printMeasurements(average, existingAverage, filter = /.*/) {
const printedLabels = Object.keys(average).filter(label => filter.test(label));
console.info('');
printedLabels.forEach(label => {
let color = text => text;
if (label[0] === '#') {
color = colorette.bold;
if (label[1] !== '#') {
color = colorette.underline;
}
}
console.info(
color(
`${label}: ${getFormattedTime(
average[label].time,
existingAverage[label] && existingAverage[label].time
)}, ${getFormattedMemory(
average[label].memory,
existingAverage[label] && existingAverage[label].memory
)}`
)
);
});
return printedLabels.length + 2;
}
function clearLines(numberOfLines) {
console.info('\33[A' + '\33[2K\33[A'.repeat(numberOfLines));
}
function getExistingTimings() {
try {
const timings = JSON.parse(fs.readFileSync(perfFile, 'utf8'));
console.info(
colorette.bold(
`Comparing with ${colorette.cyan(perfFile)}. Delete this file to create a new base line.`
)
);
return timings;
} catch (e) {
return {};
}
}
function persistTimings(timings) {
try {
fs.writeFileSync(perfFile, JSON.stringify(timings, null, 2), 'utf8');
console.info(
colorette.bold(
`Saving performance information to new reference file ${colorette.cyan(perfFile)}.`
)
);
} catch (e) {
console.error(
colorette.bold(`Could not persist performance information in ${colorette.cyan(perfFile)}.`)
);
process.exit(1);
}
}
const MIN_ABSOLUTE_TIME_DEVIATION = 10;
const RELATIVE_DEVIATION_FOR_COLORING = 5;
function getFormattedTime(currentTime, persistedTime = currentTime) {
let color = text => text,
formattedTime = `${currentTime.toFixed(0)}ms`;
const absoluteDeviation = Math.abs(currentTime - persistedTime);
if (absoluteDeviation > MIN_ABSOLUTE_TIME_DEVIATION) {
const sign = currentTime >= persistedTime ? '+' : '-';
const relativeDeviation = 100 * (absoluteDeviation / persistedTime);
formattedTime += ` (${sign}${absoluteDeviation.toFixed(
0
)}ms, ${sign}${relativeDeviation.toFixed(1)}%)`;
if (relativeDeviation > RELATIVE_DEVIATION_FOR_COLORING) {
color = currentTime >= persistedTime ? colorette.red : colorette.green;
}
}
return color(formattedTime);
}
function getFormattedMemory(currentMemory, persistedMemory = currentMemory) {
let color = text => text,
formattedMemory = prettyBytes(currentMemory);
const absoluteDeviation = Math.abs(currentMemory - persistedMemory);
const sign = currentMemory >= persistedMemory ? '+' : '-';
const relativeDeviation = 100 * (absoluteDeviation / persistedMemory);
if (relativeDeviation > RELATIVE_DEVIATION_FOR_COLORING) {
formattedMemory += ` (${sign}${relativeDeviation.toFixed(0)}%)`;
color = currentMemory >= persistedMemory ? colorette.red : colorette.green;
}
return color(formattedMemory);
}
loadPerfConfig().then(async config =>
calculatePrintAndPersistTimings(config, await getExistingTimings())
);