-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pretty_benchmark_down.ts
436 lines (382 loc) · 12.9 KB
/
pretty_benchmark_down.ts
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
import {
calculateExtraMetrics,
calculateStdDeviation,
getInThresholdRange,
getPaddedIndicator,
stripColor,
} from "./common.ts";
import type { BenchmarkResult, BenchmarkRunResult } from "./deps.ts";
import type { BenchIndicator, Thresholds } from "./types.ts";
/** Defines how the generated markdown should look like. */
export interface prettyBenchmarkDownOptions {
/** Defines a `# title` for the markdown */
title?: string;
/** Defines a section right after the `title`. When a `function` is provided, it receives the run's results */
description?: string | ((results: BenchmarkRunResult) => string);
/** Defines a section at the end of the markdown. When a `function` is provided, it receives the run's results */
afterTables?: string | ((results: BenchmarkRunResult) => string);
/** Defines `groups`, into which the benchmarks will be groupped.
* Any benchmark result, that wasn't added into any group will be collected into one table called `Ungroupped`.
* One benchmark can be in multiple groups. */
groups?: GroupDefinition[];
/** Defines the columns of the markdown tables. */
columns?: ColumnDefinition[];
}
/** Defines one column of the markdown table. */
export interface ColumnDefinition {
/** Defines the title of the column */
title: string;
/** Defines which property of the `BenchmarkResult` should be displayed, if no `formatter` is defined.
*
* *Note*: custom `propertyKey`-s can be used, but values has to be manually mapped onto each `BenchmarkResult`. */
propertyKey?: string;
/** Defines how the column should be aligned. Defaults to `center` */
align?: "left" | "center" | "right";
/** Calls `number.toFixed(x)` with this value, when defined and the cell value is a `number`.
*
* Also used on `formatter` output values. */
toFixed?: number;
/** Allows to calculate custom cell values based on the `BenchmarkResult`, and its own `ColumnDefinition`.
*
* The value will be `-` for falsy values, and `*` when no `propertyKey` and `formatter` was provided
*
* Its favoured above `propertyKey`, when both is defined.*/
formatter?: (result: BenchmarkResult, columnDef: ColumnDefinition) => string;
}
/** Defines a group in the markdown. */
export interface GroupDefinition {
/** Collects the benchmarks into the group, which `name` mathes the `RegExp` */
include: RegExp;
/** Defines the name of the group, which will be a `## Title` in the markdown */
name: string;
/** Defines the columns of the markdown table in the specific group. Overrides root and default column options. */
columns?: ColumnDefinition[];
/** Defines a section right after the `group title`. When a `function` is provided, it receives the run's results
* for the benchmarks in the group, the group's definition and the overall benchmark results. */
description?:
| string
| ((
groupResults: BenchmarkResult[],
group: GroupDefinition,
runResults: BenchmarkRunResult,
) => string);
/** Defines a section at the end of the `group`. When a `function` is provided, it receives the run's results
* for the benchmarks in the group, the group's definition and the overall benchmark results. */
afterTable?:
| string
| ((
groupResults: BenchmarkResult[],
group: GroupDefinition,
runResults: BenchmarkRunResult,
) => string);
}
/** Returns a function that expects a `BenchmarkRunResult`, which than prints
* the results in a nicely formatted `markdown`, based on the provided `options`.
*
* Without `options`, one markdown table will be generated, containing all the bench results.
*
* Typical basic usage:
*
* ```ts
* // add benches, then
* runBenchmarks().then(prettyBenchmarkDown(console.log));
* // or write to file
* runBenchmarks().then(prettyBenchmarkDown((markdown: string) => { Deno.writeTextFileSync("./benchmark.md", markdown); });
* ```
* .
*/
export function prettyBenchmarkDown(
/** Defines the output function which will be called with the generated string markdown output.*/
outputFn: (out: string) => void,
/** Defines how the output should look like */
options?: prettyBenchmarkDownOptions,
) {
return (result: BenchmarkRunResult) =>
_prettyBenchmarkDown(result, outputFn, options);
}
function _prettyBenchmarkDown(
runResult: BenchmarkRunResult,
outputFn: (out: string) => void,
options?: prettyBenchmarkDownOptions,
) {
let markdown = "";
if (options?.title) {
markdown += `# ${options.title}\n\n`;
}
markdown += stringOrFunction(options?.description, runResult) + "\n";
if (options?.groups && options.groups.length > 0) {
const grouppedResults: {
[key: string]: GroupDefinition & { items: BenchmarkResult[] };
} = {};
const unmatched: GroupDefinition & { items: BenchmarkResult[] } = {
name: "Ungrouped benches",
items: [],
// deno-lint-ignore no-explicit-any
} as any;
runResult.results.forEach((r) => {
let matched = false;
options.groups?.forEach((g, i) => {
if (r.name.match(g.include)) {
const groupProp = `${g.name}_${i}`;
if (!grouppedResults[groupProp]) {
grouppedResults[groupProp] = { ...g, items: [] };
}
grouppedResults[groupProp].items.push(r);
matched = true;
}
});
if (!matched) {
if (
!unmatched.items.some((i: BenchmarkResult) =>
i.name === r.name && i.totalMs === r.totalMs
)
) {
// if isnt already added, add to unmatched group
unmatched.items.push(r);
}
}
});
grouppedResults[`${unmatched.name}_${options.groups.length}`] = unmatched;
const optionsGroup = [...options.groups];
if (unmatched.items.length > 0) {
optionsGroup.push(unmatched);
}
optionsGroup.forEach((g, i) => { // to keep order works from options.
markdown += `## ${g.name}\n\n`;
const resultGroup = grouppedResults[`${g.name}_${i}`];
markdown += stringOrFunction(
g.description,
resultGroup?.items || [],
g,
runResult,
);
if (resultGroup) {
markdown += headerRow(options, g);
resultGroup.items.forEach((r: BenchmarkResult) => {
markdown += tableRow(r, options, g);
});
} else {
markdown += "> No benchmarks in this group.\n";
}
markdown += "\n";
markdown += stringOrFunction(
g.afterTable,
resultGroup?.items || [],
g,
runResult,
) + "\n";
});
} else {
markdown += headerRow(options);
runResult.results.forEach((r) => {
markdown += tableRow(r, options);
});
markdown += "\n";
}
markdown += stringOrFunction(options?.afterTables, runResult) + "\n";
outputFn(markdown);
return runResult;
}
const defaultColumnsArray: ColumnDefinition[] = [
{ title: "Name", propertyKey: "name", align: "left" },
{ title: "Runs", propertyKey: "runsCount", align: "right" },
{ title: "Total (ms)", propertyKey: "totalMs", align: "right", toFixed: 3 },
{
title: "Average (ms)",
propertyKey: "measuredRunsAvgMs",
align: "right",
toFixed: 3,
},
];
/** Defines the default `ColumnDefinitions`, which are `Name`, `Runs`, `Total (ms)` and `Average (ms)` */
export function defaultColumns(
columns?: ("name" | "runsCount" | "totalMs" | "measuredRunsAvgMs")[],
): ColumnDefinition[] {
if (columns) {
return [...defaultColumnsArray].filter((dc) =>
(columns as string[]).indexOf(dc.propertyKey!) !== -1
);
} else {
return [...defaultColumnsArray];
}
}
/** Defines a column which contains the indicators for the benchmarks, where provided.
*
* *Note*: colors are stripped from the indicators in markdown */
export function indicatorColumn(
indicators: BenchIndicator[],
): ColumnDefinition {
return {
title: "",
formatter: (result: BenchmarkResult, cd: ColumnDefinition) => {
return stripColor(getPaddedIndicator(result.name, 0, indicators));
},
};
}
/** Defines a threshold result column, which shows into which range the benchmark fell. Shows `-` when no `Threshold` was provided for the given benchmark. */
export function thresholdResultColumn(thresholds: Thresholds) {
return {
title: "",
formatter: (result: BenchmarkResult, cd: ColumnDefinition) => {
const inRange = getInThresholdRange(
result.name,
result.measuredRunsAvgMs,
thresholds,
);
return ["-", "✅", "🔶", "🔴"][inRange || 0];
},
};
}
/** Defines a threshold result column, which shows the threshold ranges for the benchmark. Shows `-` when no `Threshold` was provided for the given benchmark.
*
* If `indicateResult` is set, it shows in the same cell into which range the benchmark fell.*/
export function thresholdsColumn(
thresholds: Thresholds,
indicateResult?: boolean,
) {
return {
title: "Thresholds",
align: "right",
formatter: (result: BenchmarkResult, cd: ColumnDefinition) => {
let value = "<small>";
const inRange = getInThresholdRange(
result.name,
result.measuredRunsAvgMs,
thresholds,
);
const th = thresholds && thresholds[result.name];
if (!th) {
return "-";
}
const indicator = " 🠴";
const placeholder = " ";
value += `<= ${th.green} ✅` +
(indicateResult ? (inRange === 1 ? indicator : placeholder) : "") +
"<br>";
value += `<= ${th.yellow} 🔶` +
(indicateResult ? (inRange === 2 ? indicator : placeholder) : "") +
"<br>";
value += ` > ${th.yellow} 🔴` +
(indicateResult ? (inRange === 3 ? indicator : placeholder) : "");
value += "</small>";
return value;
},
};
}
/** Defines **multiple** columns, which contain extra calculated values, like `max`, `min`, `mean`, `median`, `stdDeviation`.
*
* Can be used like:
* ```ts
* columns: [...extraMetricsColumns()]
* ```
* . */
export function extraMetricsColumns(
options?: {
/** Defines which metrics it should include */
metrics?: ("max" | "min" | "mean" | "median" | "stdDeviation")[];
/** If set, `-` will be placed into cells, where the benchmark was only run once. */
ignoreSingleRuns?: boolean;
},
): ColumnDefinition[] {
const columns: ColumnDefinition[] = [];
const selected = options?.metrics ||
["min", "max", "mean", "median", "stdDeviation"];
selected.forEach((s) => {
if (s === "stdDeviation") {
columns.push({
title: "Std deviation",
align: "right",
toFixed: 3,
formatter: (result: BenchmarkResult, cd: ColumnDefinition) => {
if (options?.ignoreSingleRuns && result.runsCount === 1) {
return "-";
}
const calced = calculateStdDeviation(result);
return `${calced}`;
},
});
} else {
columns.push({
title: s.charAt(0).toUpperCase() + s.slice(1), // capitalise
align: "right",
toFixed: 3,
formatter: (result: BenchmarkResult, cd: ColumnDefinition) => {
if (options?.ignoreSingleRuns && result.runsCount === 1) {
return "-";
}
const calced = calculateExtraMetrics(result);
return `${calced[s]}`;
},
});
}
});
return columns;
}
function stringOrFunction(
// deno-lint-ignore no-explicit-any
value?: ((...params: any[]) => string) | string,
// deno-lint-ignore no-explicit-any
...params: any[]
) {
if (!value) {
return "";
}
if (typeof value === "function") {
return `${value(...params)}\n`;
} else {
return `${value}\n`;
}
}
function headerRow(
options?: prettyBenchmarkDownOptions,
group?: GroupDefinition,
) {
let titles = "|";
let alignments = "|";
const columns: ColumnDefinition[] = group?.columns || options?.columns ||
defaultColumns();
columns.forEach((c) => {
titles += `${c.title}|`;
alignments += `${alignment(c.align)}|`;
});
return `${titles}\n${alignments}\n`;
}
function tableRow(
result: BenchmarkResult,
options?: prettyBenchmarkDownOptions,
group?: GroupDefinition,
) {
let values = `|`;
const columns: ColumnDefinition[] = group?.columns || options?.columns ||
defaultColumns();
columns.forEach((c) => {
let value = null;
if (typeof c.formatter === "function") {
value = `${c.formatter(result, c)}`;
} else {
if (!c.propertyKey) {
value = "*"; // this means no formatter function and no propertyKey was defined.
} else {
// deno-lint-ignore no-explicit-any
const vc = (result as any)[c.propertyKey];
value = typeof vc !== "undefined" ? vc : "-";
}
}
if (!isNaN(parseFloat(value)) && !isNaN(c.toFixed!)) {
value = parseFloat(value).toFixed(c.toFixed);
}
values += `${value}|`;
});
return `${values}\n`;
}
function alignment(mode?: "left" | "center" | "right") {
if (mode === "right") {
return "--:";
}
if (!mode || mode === "center") {
return ":-:";
}
if (mode === "left") {
return ":--";
}
}