/
perf.js
208 lines (192 loc) · 6.42 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
204
205
206
207
208
/* eslint-disable import/no-unresolved */
/* global gc */
import { readFileSync, writeFileSync } from 'node:fs';
import { argv, chdir, cwd, exit } from 'node:process';
import { fileURLToPath } from 'node:url';
import { createColors } from 'colorette';
import prettyBytes from 'pretty-bytes';
import { loadConfigFile } from '../dist/loadConfigFile.js';
import { rollup } from '../dist/rollup.js';
import { findConfigFileName } from './find-config.js';
const initialDirectory = cwd();
const targetDirectory = fileURLToPath(new URL('../perf', import.meta.url).href);
const perfFile = fileURLToPath(new URL('../perf/rollup.perf.json', import.meta.url).href);
const { bold, underline, cyan, red, green } = createColors();
const MIN_ABSOLUTE_TIME_DEVIATION = 10;
const RELATIVE_DEVIATION_FOR_COLORING = 5;
chdir(targetDirectory);
const configFile = await findConfigFileName(targetDirectory);
const configs = await loadConfigFile(
configFile,
configFile.endsWith('.ts') ? { configPlugin: 'typescript' } : {}
);
let numberOfRunsToAverage = 6;
let numberOfDiscardedResults = 3;
if (argv.length >= 3) {
numberOfRunsToAverage = Number.parseInt(argv[2]);
if (argv.length >= 4) {
numberOfDiscardedResults = Number.parseInt(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>'
);
exit(1);
}
console.info(
bold(
`Calculating the average of ${cyan(numberOfRunsToAverage)} runs discarding the ${cyan(
numberOfDiscardedResults
)} largest results.\n`
) + 'Run "npm run perf <number of runs> <number of discarded results>" to change that.'
);
await calculatePrintAndPersistTimings(configs.options[0], await getExistingTimings());
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 = {};
for (const label of Object.keys(accumulatedMeasurements)) {
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);
for (const label of Object.keys(timings)) {
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);
for (const label of Object.keys(timings)) {
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();
chdir(targetDirectory);
const bundle = await rollup(config);
chdir(initialDirectory);
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('');
for (const label of printedLabels) {
let color = identity;
if (label[0] === '#') {
color = bold;
if (label[1] !== '#') {
color = 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('\u001B[A' + '\u001B[2K\u001B[A'.repeat(numberOfLines));
}
function getExistingTimings() {
try {
const timings = JSON.parse(readFileSync(perfFile, 'utf8'));
console.info(
bold(`Comparing with ${cyan(perfFile)}. Delete this file to create a new base line.`)
);
return timings;
} catch {
return {};
}
}
function persistTimings(timings) {
try {
writeFileSync(perfFile, JSON.stringify(timings, null, 2), 'utf8');
console.info(bold(`Saving performance information to new reference file ${cyan(perfFile)}.`));
} catch {
console.error(bold(`Could not persist performance information in ${cyan(perfFile)}.`));
exit(1);
}
}
function getFormattedTime(currentTime, persistedTime = currentTime) {
let color = identity,
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 ? red : green;
}
}
return color(formattedTime);
}
function getFormattedMemory(currentMemory, persistedMemory = currentMemory) {
let color = identity,
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 ? red : green;
}
return color(formattedMemory);
}
function identity(x) {
return x;
}