Repository navigation
Expand file tree
/
Copy pathcompilerBenchmarks.js
More file actions
1412 lines (1341 loc) · 48.9 KB
/
Copy pathcompilerBenchmarks.js
File metadata and controls
1412 lines (1341 loc) · 48.9 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// @ts-check
// Compiler benchmarks: compare how much memory the compiler allocates, and
// how many instructions it executes, on a fixed set of inputs, before and
// after a change.
//
// Wall-clock and CPU time are too noisy on shared CI runners to alert on, so
// these benchmarks count instead:
//
// - the words the compiler allocates, which the OCaml runtime reports at exit
// (OCAMLRUNPARAM=v=0x400). The count is the same in every run of the same
// binary on the same input from the same path; other paths change it by a
// few words. The peak heap size is reported too, but isn't usable:
// it depends on when collections happen, and a few more words allocated
// move it by several percent.
// - the instructions it executes, which cachegrind reports at exit
// (`valgrind --tool=cachegrind --cache-sim=no`), for a subset of the
// benchmarks, since valgrind runs a program 20 to 50 times slower. This
// catches slowdowns that don't allocate, such as a scan of a list that
// already exists.
// - the sizes of the compiler's outputs (.cmi, .cmti, .cmt and .cmj files,
// and the playground's compiler), which are exact.
//
// node scripts/compilerBenchmarks.js prepare <checkout>
// node scripts/compilerBenchmarks.js measure <checkout> <out.json> [--instructions]
// [--project <checkout>] [--playground]
// node scripts/compilerBenchmarks.js time <base checkout> <head checkout>
// <out.json> [--rounds <n>]
// node scripts/compilerBenchmarks.js compare <base.json> <head.json>
// [--threshold <percent>] [--summary <file.md>]
//
// `prepare` builds the runtime and Belt of a checkout whose compiler is
// built. `measure` runs the binaries of a prepared checkout: it replays the
// build of every runtime and Belt source file, one file at a time, with the
// arguments `rescript compiler-args` gives for it, compiles a few generated
// inputs that stress parts of the compiler that were superlinear at some
// point, and parses and formats the large files in tests/compiler_benchmarks/data
// (the build never runs the formatter). With `--instructions`, the generated
// inputs, the data files and the largest runtime and Belt files run under
// cachegrind. The generated inputs and the data files come from the checkout
// of this script, so both measurements use the same ones. With `--project`,
// it also builds tests/tests of the given checkout with the build system,
// clean, with nothing to do and after two edits (see measureProjectBuild),
// and a few generated projects, clean and after an edit, for costs that grow
// with the number of modules of a build (see generatedProjects), counting
// allocated words only.
// With `--playground`, it measures the size of the playground's compiler.
//
// `time` builds a generated project with the build systems of two prepared
// checkouts in turn, writes the wall-clock times to <out.json> and prints
// their medians and the median ratio of the head's time to the base's with
// a 95% confidence interval (see timeBuilds). It is the one benchmark that
// measures time, run by hand to indicate the effect of a change that does
// the same work sooner; CI doesn't run it.
//
// `compare` reports the changes between two measurements as Markdown,
// improvements and regressions alike, one section per count, and exits with
// 1 when a count grew by more than the threshold. Runtime and Belt files,
// whose sources the two checkouts may not share, are reported but not
// alerted on when any of them differs.
import { execFileSync, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { binDir } from "#cli/bins";
const repoRoot = path.join(import.meta.dirname, "..");
/** The platform binaries' directory, relative to a checkout's root. */
const relativeBinDir = path.relative(repoRoot, binDir);
/** Large files to parse and format, from the checkout of this script. */
const dataDir = path.join(repoRoot, "tests", "compiler_benchmarks", "data");
/** The packages whose sources are replayed, with their source directories. */
const packages = [
{ dir: "packages/@rescript/runtime", sources: "." },
{ dir: "packages/@rescript/belt", sources: "src" },
];
/**
* How many of the largest runtime and Belt sources run under cachegrind.
* They are chosen by size in the checkout of this script, so that both
* measurements choose the same files.
*/
const instructionPackageFiles = 15;
/**
* The minor heap of the runs under cachegrind, in words. A few words more or
* less allocated, as from paths of different lengths, move the points where
* the garbage collector runs, and with them how much of a major cycle is
* done before the program exits: that changed instruction counts by up to 3%
* between two builds of the same compiler. With a minor heap larger than
* any benchmark allocates (35M words at most), the collector doesn't run,
* and the instructions are the compiler's own; the cost of collecting is in
* the allocated words, which these settings don't change. The heap is
* mapped only as it's used, but OCaml reserves address space for a minor
* heap per possible domain (128 by default), more than valgrind can give,
* so the runs allow only the one domain bsc uses (d=1).
*/
const cachegrindRuntimeParams = "v=0x400,d=1,s=64M";
/**
* `inputs` is a hash of everything besides the compiler that the counts
* depend on. `instructions` is only measured for some benchmarks, and
* `bytes`, the size of an output, only for outputs.
*
* @typedef {{
* allocated?: number,
* instructions?: number,
* bytes?: number,
* inputs: string,
* }} Measurement
* @typedef {Record<string, Measurement>} Results
* @typedef {"allocated" | "instructions" | "bytes"} Metric
*/
/**
* Reads the allocated words that OCAMLRUNPARAM=v=0x400 prints to stderr at
* exit.
*
* @param {string} stderr
* @returns {number | undefined}
*/
export function parseAllocatedWords(stderr) {
const match = /^allocated_words: (\d+)$/m.exec(stderr);
if (!match) return undefined;
// The build system compiles on worker domains, whose allocations the
// runtime leaves out; it reports them itself when asked to
// (RESCRIPT_REPORT_WORKER_ALLOCATIONS).
const workers = /^worker_allocated_words: (\d+)$/m.exec(stderr);
return Number(match[1]) + (workers ? Number(workers[1]) : 0);
}
/**
* Reads the instructions that cachegrind prints to stderr at exit, as in
* `==1234== I refs: 12,345,678`.
*
* @param {string} stderr
* @returns {number | undefined}
*/
export function parseInstructions(stderr) {
const match = /^==\d+== I\s+refs:\s+([\d,]+)\s*$/m.exec(stderr);
return match ? Number(match[1].replaceAll(",", "")) : undefined;
}
/**
* Runs an OCaml executable and returns the words it allocated and, under
* cachegrind, the instructions it executed.
*
* @param {string} exe
* @param {string[]} args
* @param {string} cwd
* @param {boolean} instructions
* @param {{ env?: Record<string, string> }} [options] extra environment
* variables
* @returns {{ allocated: number, instructions?: number }}
*/
function measureRun(exe, args, cwd, instructions, { env = {} } = {}) {
const [command, commandArgs] = instructions
? [
"valgrind",
[
"--tool=cachegrind",
"--cache-sim=no",
"--cachegrind-out-file=/dev/null",
exe,
...args,
],
]
: [exe, args];
const result = spawnSync(command, commandArgs, {
cwd,
encoding: "utf8",
maxBuffer: 256 * 1024 * 1024,
env: {
...process.env,
...env,
OCAMLRUNPARAM: instructions ? cachegrindRuntimeParams : "v=0x400",
},
});
const stderr = result.stderr ?? "";
const allocated = parseAllocatedWords(stderr);
const executed = instructions ? parseInstructions(stderr) : undefined;
if (
result.status !== 0 ||
allocated === undefined ||
(instructions && executed === undefined)
) {
const reason = result.error
? result.error.message
: `exit ${result.status}`;
throw new Error(
`${command} ${commandArgs.join(" ")} failed in ${cwd} (${reason}):\n${stderr}`,
);
}
return executed === undefined
? { allocated }
: { allocated, instructions: executed };
}
/**
* Adds up the counts of the runs of one benchmark.
*
* @param {{ allocated: number, instructions?: number }[]} runs
*/
function sumRuns(runs) {
const allocated = runs.reduce((sum, run) => sum + run.allocated, 0);
if (runs.some(run => run.instructions === undefined)) return { allocated };
const instructions = runs.reduce(
(sum, run) => sum + (run.instructions ?? 0),
0,
);
return { allocated, instructions };
}
/**
* A short hash of the files' names and contents.
*
* @param {string[]} files
*/
function hashFiles(files) {
const hash = createHash("sha256");
for (const file of files) {
hash.update(path.basename(file)).update("\0");
hash.update(fs.readFileSync(file)).update("\0");
}
return hash.digest("hex").slice(0, 16);
}
/**
* Generated inputs, one for each part of the compiler that was superlinear
* at some point. They are small enough to compile in well under a second,
* and each allocates less than the minor heap of the runs under cachegrind
* (see cachegrindRuntimeParams).
*
* @type {Record<string, () => string>}
*/
export const stressInputs = {
// Exhaustiveness and unused-case checks, and the match compiler.
IntSwitch: () => {
const cases = Array.from(
{ length: 1500 },
(_, i) => ` | ${i} => ${i * 7}`,
);
return `let f = x =>\n switch x {\n${cases.join("\n")}\n | _ => -1\n }\n`;
},
PolyVariantSwitch: () => {
const tags = Array.from({ length: 400 }, (_, i) => `#Tag${i}`);
const cases = tags.map((tag, i) => ` | ${tag} => ${i}`);
return `type t = [${tags.join(" | ")}]\nlet f = (x: t) =>\n switch x {\n${cases.join("\n")}\n }\n`;
},
// Pattern variables of a let rec, and the Lambda SCC of its bindings.
LetRec: () => {
const bindings = Array.from(
{ length: 2000 },
(_, i) =>
`and f${i} = x => if x <= 0 { 0 } else { f${(i + 1) % 2000}(x - 1) + ${i} }`,
);
return `let rec start = x => f0(x)\n${bindings.join("\n")}\n`;
},
// Label disambiguation and record spreads.
Record: () => {
const fields = Array.from({ length: 300 }, (_, i) => `f${i}`);
return [
`type t = {${fields.map(f => `${f}: int`).join(", ")}}`,
`let r = {${fields.map((f, i) => `${f}: ${i}`).join(", ")}}`,
...fields.map((f, i) => `let r${i} = {...r, ${f}: r.${f} + 1}`),
"",
].join("\n");
},
// The JavaScript printer's output for nested constructors.
ListLiteral: () => {
const items = Array.from({ length: 3000 }, (_, i) => `${i}`);
return `let l = list{${items.join(", ")}}\n`;
},
// Inlining of functions whose bodies were inlined already.
InlineChain: () => {
const fns = Array.from(
{ length: 300 },
(_, i) => `let f${i + 1} = x => f${i}(x) + ${i + 1}`,
);
return `let f0 = x => x\n${fns.join("\n")}\n`;
},
// Field access on a large object type: each access instantiates a copy
// of the whole type. Quadratic in the number of fields.
ObjectFields: () => {
const fields = Array.from({ length: 400 }, (_, i) => `f${i}`);
return [
`let o = {${fields.map((f, i) => `"${f}": ${i}`).join(", ")}}`,
...fields.map((f, i) => `let a${i} = o["${f}"] + 1`),
"",
].join("\n");
},
// Expansion of type aliases that refer to the previous one, with the
// cycle check of each new definition. Cubic in the length of the chain.
TypeAliasChain: () => {
const length = 60;
const aliases = Array.from(
{ length },
(_, i) => `type t${i + 1}<'a> = t${i}<('a, int)>`,
);
return `type t0<'a> = option<'a>\n${aliases.join("\n")}\nlet x: t${length}<string> = None\n`;
},
// Many mutable references updated in one loop. Superlinear in their
// number although the input is linear.
RefsInLoop: () => {
const refs = Array.from({ length: 300 }, (_, i) => `r${i}`);
return [
"let f = n => {",
...refs.map((r, i) => ` let ${r} = ref(${i})`),
" for i in 0 to n {",
...refs.map((r, i) => ` ${r} := ${r}.contents + i * ${i + 1}`),
" }",
` ${refs.map(r => `${r}.contents`).join(" + ")}`,
"}",
"",
].join("\n");
},
// Closures nested in closures, each using the variables of all outer ones.
NestedClosures: () => {
const depth = 100;
const lines = ["let f = x0 => {"];
for (let i = 1; i < depth; i++) {
const used = Array.from({ length: i }, (_, j) => `x${j}`).join(" + ");
lines.push(`${" ".repeat(i)}let g${i} = x${i} => {`);
lines.push(`${" ".repeat(i + 1)}let y${i} = ${used} + x${i}`);
}
lines.push(`${" ".repeat(depth)}y${depth - 1}`);
for (let i = depth - 1; i >= 1; i--) {
lines.push(`${" ".repeat(i)}}`);
lines.push(`${" ".repeat(i)}g${i}(${i})`);
}
lines.push("}", "");
return lines.join("\n");
},
};
/**
* A generated project: its files by path relative to its root, rescript.json
* among them, and the source file that its edit changes.
*
* @typedef {{ files: Record<string, string>, edit: string }} GeneratedProject
*/
/**
* The rescript.json of a generated project, with JavaScript written to lib/
* so that removing lib/ makes the next build a clean one.
*
* @param {string} name
* @param {Record<string, unknown>} [extra] more settings
*/
function projectConfig(name, extra = {}) {
const config = {
name,
sources: [{ dir: "src" }],
"package-specs": { module: "esmodule", "in-source": false },
suffix: ".mjs",
...extra,
};
return `${JSON.stringify(config, null, 2)}\n`;
}
/**
* Generated projects for the build benchmarks, one for each cost of a build
* that grows with the number of modules rather than with their size, which
* compiling one file at a time doesn't show. Their modules are small, so
* each builds in a few seconds at most.
*
* @type {Record<string, () => GeneratedProject>}
*/
export const generatedProjects = {
// Many modules that each use one or two values of a few large
// dependencies: the cost of loading a dependency's interface, which the
// type checker copies when it reads it, against the little of it that is
// used.
WideDeps: () => {
const dependencies = 4;
const values = 600;
const users = 240;
/** @type {Record<string, string>} */
const files = { "rescript.json": projectConfig("bench-wide-deps") };
for (let d = 0; d < dependencies; d++) {
const lines = [];
for (let v = 0; v < values; v++) {
lines.push(`type t${v} = {a${v}: int, b${v}: string}`);
lines.push(
`let make${v} = (x: int): t${v} => {a${v}: x, b${v}: "${v}"}`,
);
lines.push(`let get${v} = (r: t${v}) => r.a${v} + ${v}`);
}
files[`src/Big${d}.res`] = `${lines.join("\n")}\n`;
}
for (let u = 0; u < users; u++) {
const first = u % dependencies;
const second = (u * 7 + 1) % dependencies;
const v = (u * 37) % values;
files[`src/User${u}.res`] = [
`let a = Big${first}.get${v}(Big${first}.make${v}(${u}))`,
`let b = Big${second}.make${(v + 1) % values}(a).b${(v + 1) % values}`,
"",
].join("\n");
}
// A new value in a dependency changes its interface, so every module
// that uses it is compiled again.
return { files, edit: "src/Big0.res" };
},
// A namespaced package of trivial modules. Each module opens the
// namespace's map of module aliases, one for every module of the package,
// so a cost per alias of opening it is quadratic in the package's size.
Namespace: () => {
const modules = 1000;
/** @type {Record<string, string>} */
const files = {
"rescript.json": projectConfig("bench-namespace", { namespace: true }),
};
for (let i = 0; i < modules; i++) {
// Each module but the first uses another one, through the map.
const use = i === 0 ? "0" : `Mod${Math.floor((i - 1) / 2)}.value`;
files[`src/Mod${i}.res`] = `let value = ${use} + ${i}\n`;
}
// The last module, which nothing uses.
return { files, edit: `src/Mod${modules - 1}.res` };
},
};
/**
* The project the wall-time benchmark builds: a long chain of modules, each
* using the one before it, and a module beside each that uses it. A build
* spends most of its time on the chain with most of its worker domains
* idle, which is what a change to the build's scheduling would improve.
*
* @returns {GeneratedProject}
*/
export function chainProject() {
const length = 150;
/** @type {Record<string, string>} */
const files = { "rescript.json": projectConfig("bench-chain") };
for (let i = 0; i < length; i++) {
const lines =
i === 0
? [
"type t = {depth: int, items: array<int>}",
"let base = {depth: 0, items: []}",
]
: [
`type t = {depth: int, items: array<int>, prev: Chain${i - 1}.t}`,
`let base = {depth: ${i}, items: [${i}], prev: Chain${i - 1}.base}`,
];
// Bodies with some work for the type checker and code generation.
for (let f = 0; f < 20; f++) {
lines.push(
`let f${f} = (r: t, x: int) =>`,
" switch mod(x, 4) {",
` | 0 => r.items->Array.map(y => y + x + ${f})->Array.length`,
` | 1 => r.depth * ${f + 1} + x`,
` | 2 => r.items->Array.reduce(0, (acc, y) => acc + y * ${f})`,
" | _ => -1",
" }",
);
}
files[`src/Chain${i}.res`] = `${lines.join("\n")}\n`;
files[`src/Side${i}.res`] = [
`let total = Chain${i}.f0(Chain${i}.base, ${i}) + Chain${i}.f1(Chain${i}.base, 1)`,
"",
].join("\n");
}
return { files, edit: `src/Chain${length - 1}.res` };
}
/**
* The runtime and Belt sources of a checkout, by package.
*
* @param {string} checkout
*/
function packageSources(checkout) {
return packages.flatMap(pkg => {
const sourceDir = path.join(checkout, pkg.dir, pkg.sources);
return fs
.readdirSync(sourceDir)
.filter(file => file.endsWith(".res") || file.endsWith(".resi"))
.sort()
.map(file => ({
pkg,
file,
name: `${pkg.dir}/${path.posix.join(pkg.sources, file)}`,
sourcePath: path.join(sourceDir, file),
}));
});
}
/**
* Builds the runtime and Belt of a checkout whose compiler is built, with
* that checkout's build system. A checkout made with `git worktree add` has
* no node_modules; the build system only needs to find @rescript/runtime.
*
* @param {string} checkout
*/
export function prepare(checkout) {
const scope = path.join(checkout, "node_modules", "@rescript");
const runtimeLink = path.join(scope, "runtime");
if (!fs.existsSync(runtimeLink)) {
fs.mkdirSync(scope, { recursive: true });
fs.symlinkSync(
path.join("..", "..", "packages", "@rescript", "runtime"),
runtimeLink,
"junction",
);
}
const rescript = path.join(checkout, relativeBinDir, "rescript.exe");
for (const pkg of packages) {
execFileSync(rescript, ["build"], {
cwd: path.join(checkout, pkg.dir),
stdio: "inherit",
});
}
}
/**
* The playground's compiler that `make playground-compiler` builds, relative
* to a checkout's root.
*/
const playgroundCompiler = path.join("packages", "playground", "compiler.js");
/** The interface and artifact files whose sizes are measured. */
const outputExtensions = [".cmi", ".cmti", ".cmt", ".cmj"];
/**
* The files in a directory and its subdirectories, sorted. Symbolic links
* aren't followed: the projects link to the runtime, whose outputs are
* measured on their own.
*
* @param {string} dir
* @returns {string[]}
*/
function listFiles(dir) {
return fs
.readdirSync(dir, { withFileTypes: true })
.sort((a, b) => a.name.localeCompare(b.name))
.flatMap(entry => {
const file = path.join(dir, entry.name);
if (entry.isDirectory()) return listFiles(file);
return entry.isFile() ? [file] : [];
});
}
/**
* The total size of the files in a directory and its subdirectories, by
* extension.
*
* @param {string} dir
* @returns {Record<string, number>}
*/
function outputSizes(dir) {
/** @type {Record<string, number>} */
const sizes = Object.fromEntries(outputExtensions.map(ext => [ext, 0]));
for (const file of listFiles(dir)) {
const ext = path.extname(file);
if (ext in sizes) sizes[ext] += fs.statSync(file).size;
}
return sizes;
}
/**
* Copies the ReScript sources of a directory and its subdirectories, and
* nothing else: the outputs the tests check in are written by the builds.
*
* @param {string} from
* @param {string} to
*/
function copySources(from, to) {
fs.cpSync(from, to, {
recursive: true,
filter: source =>
fs.statSync(source).isDirectory() ||
source.endsWith(".res") ||
source.endsWith(".resi"),
});
}
/** The project the build benchmarks build, relative to a checkout. */
const benchmarkProject = path.join("tests", "tests");
/**
* The module of the project that about 200 others use, and that has no
* interface file, so that an edit changes its interface.
*/
const sharedModule = path.join("src", "test_utils.res");
/**
* Builds tests/tests of `projectCheckout` with the build system of
* `checkout`, on one worker domain so that the counts don't depend on how
* the work is shared: a clean build, a build with nothing to do, and the
* builds after an edit of a module that nothing uses and of one that many
* do. Adds the sizes of the outputs of the clean build.
*
* The project is copied to a directory of its own, with the same name in
* every measurement, so that no path of the checkout enters the counts.
* Both measurements build the same sources, those of the base, which its
* compiler builds already; warnings are no errors there, so that a new
* warning doesn't fail the build.
*
* The builds don't run under cachegrind: a ticker wakes the build's
* scheduler every 5 ms of wall-clock time, so their instructions depend on
* how fast the machine runs them; the leaf-edit build's grew by 348% in a
* pull request that didn't change its allocations.
*
* @param {string} checkout
* @param {string} projectCheckout
* @param {Results} results
*/
function measureProjectBuild(checkout, projectCheckout, results) {
const rescript = path.join(checkout, relativeBinDir, "rescript.exe");
const projectDir = path.join(projectCheckout, benchmarkProject);
const workDir = path.join(os.tmpdir(), "compiler-bench-project");
fs.rmSync(workDir, { recursive: true, force: true });
try {
copySources(path.join(projectDir, "src"), path.join(workDir, "src"));
const config = JSON.parse(
fs.readFileSync(path.join(projectDir, "rescript.json"), "utf8"),
);
config["compiler-flags"] = (config["compiler-flags"] ?? []).filter(
(/** @type {string} */ flag) => !flag.startsWith("-warn-error"),
);
fs.writeFileSync(
path.join(workDir, "rescript.json"),
`${JSON.stringify(config, null, 2)}\n`,
);
const scope = path.join(workDir, "node_modules", "@rescript");
const react = path.join(
projectCheckout,
"tests",
"dependencies",
"rescript-react",
);
copySources(path.join(react, "src"), path.join(scope, "react", "src"));
fs.copyFileSync(
path.join(react, "rescript.json"),
path.join(scope, "react", "rescript.json"),
);
fs.symlinkSync(
path.join(checkout, "packages", "@rescript", "runtime"),
path.join(scope, "runtime"),
"junction",
);
const sources = listFiles(workDir).filter(
file => file.endsWith(".res") || file.endsWith(".resi"),
);
const inputs = hashFiles(sources);
// The largest test, which no other module uses.
const leafModule = sources
.filter(file => path.dirname(file) === path.join(workDir, "src"))
.filter(file => file.endsWith("_test.res"))
.map(file => ({ file, size: fs.statSync(file).size }))
.sort((a, b) => b.size - a.size || a.file.localeCompare(b.file))[0]?.file;
if (!leafModule || !fs.existsSync(path.join(workDir, sharedModule))) {
throw new Error(`The modules to edit are missing from ${projectDir}.`);
}
const build = () => countBuild(rescript, workDir, inputs);
results["build/clean"] = build();
const outputs = outputSizes(workDir);
for (const ext of outputExtensions) {
results[`output/tests/*${ext}`] = { bytes: outputs[ext], inputs };
}
results["build/no-op"] = build();
editModule(leafModule);
results["build/leaf-edit"] = build();
editModule(path.join(workDir, sharedModule));
results["build/shared-edit"] = build();
} finally {
fs.rmSync(workDir, { recursive: true, force: true });
}
}
/**
* Builds a project with a build system on one worker domain, so that the
* counts don't depend on how the work is shared, and counts the words it
* and its workers allocated.
*
* @param {string} rescript
* @param {string} dir
* @param {string} inputs
* @returns {Measurement}
*/
function countBuild(rescript, dir, inputs) {
return {
...measureRun(rescript, ["build"], dir, false, {
env: {
RESCRIPT_COMPILER_DOMAINS: "1",
RESCRIPT_REPORT_WORKER_ALLOCATIONS: "1",
},
}),
inputs,
};
}
/**
* Adds a value to a module, which changes its interface when it has no
* interface file.
*
* @param {string} file
*/
function editModule(file) {
fs.appendFileSync(file, "\nlet benchmarkEdit = 1\n");
}
/**
* Writes a generated project to an empty directory, with the runtime of
* `checkout` as its only dependency. Returns a hash of its files.
*
* @param {GeneratedProject} project
* @param {string} dir
* @param {string} checkout
*/
function writeProject(project, dir, checkout) {
const hash = createHash("sha256");
for (const [file, contents] of Object.entries(project.files)) {
fs.mkdirSync(path.join(dir, path.dirname(file)), { recursive: true });
fs.writeFileSync(path.join(dir, file), contents);
hash.update(file).update("\0").update(contents).update("\0");
}
const scope = path.join(dir, "node_modules", "@rescript");
fs.mkdirSync(scope, { recursive: true });
fs.symlinkSync(
path.join(checkout, "packages", "@rescript", "runtime"),
path.join(scope, "runtime"),
"junction",
);
return hash.digest("hex").slice(0, 16);
}
/**
* Builds each generated project with the build system of `checkout`, clean
* and after its edit, counting allocated words like measureProjectBuild.
* The projects come from the checkout of this script, and are built in a
* directory with the same name in every measurement.
*
* @param {string} checkout
* @param {Results} results
*/
function measureGeneratedProjects(checkout, results) {
const rescript = path.join(checkout, relativeBinDir, "rescript.exe");
const workDir = path.join(os.tmpdir(), "compiler-bench-generated");
for (const [name, generate] of Object.entries(generatedProjects)) {
fs.rmSync(workDir, { recursive: true, force: true });
try {
const project = generate();
const inputs = writeProject(project, workDir, checkout);
results[`build/${name}/clean`] = countBuild(rescript, workDir, inputs);
editModule(path.join(workDir, project.edit));
results[`build/${name}/edit`] = countBuild(rescript, workDir, inputs);
} finally {
fs.rmSync(workDir, { recursive: true, force: true });
}
}
}
/**
* @param {string} checkout
* @param {{ instructions: boolean, project?: string, playground?: boolean }} options
* `project` is the checkout whose tests/tests the build benchmarks build;
* without it, there are none. `playground` adds the size of the
* playground's compiler, which must be built.
* @returns {Results}
*/
export function measure(checkout, { instructions, project, playground }) {
const bins = path.join(checkout, relativeBinDir);
const bsc = path.join(bins, "bsc.exe");
const rescript = path.join(bins, "rescript.exe");
/** @type {Results} */
const results = {};
const sources = packageSources(checkout);
// Each file is compiled against the interfaces of the others, so a change
// to any of them can change what compiling it allocates.
const packageInputs = hashFiles(sources.map(s => s.sourcePath));
const underCachegrind = new Set(
instructions
? packageSources(repoRoot)
.map(s => ({ name: s.name, size: fs.statSync(s.sourcePath).size }))
.sort((a, b) => b.size - a.size || a.name.localeCompare(b.name))
.slice(0, instructionPackageFiles)
.map(s => s.name)
: [],
);
// One file at a time: the runs write the outputs of the build again, and
// read the outputs of the files they depend on.
for (const { pkg, name, sourcePath } of sources) {
const { parser_args, compiler_args } = JSON.parse(
execFileSync(rescript, ["compiler-args", sourcePath], {
encoding: "utf8",
}),
);
// The build parses into lib/rescript, then compiles the AST there. The
// outputs these runs write are the ones the build wrote already.
const libDir = path.join(checkout, pkg.dir, "lib", "rescript");
const cachegrind = underCachegrind.has(name);
results[name] = {
...sumRuns([
measureRun(bsc, parser_args, libDir, cachegrind),
measureRun(bsc, compiler_args, libDir, cachegrind),
]),
inputs: packageInputs,
};
}
// The generated inputs and the data files are compiled in a directory of
// their own under relative names, so that no path of the checkout enters
// their counts. The directory has the same name in every measurement, so
// that two measurements of the same compiler give the same counts; they
// can't run at the same time.
const workDir = path.join(os.tmpdir(), "compiler-bench");
fs.rmSync(workDir, { recursive: true, force: true });
fs.mkdirSync(workDir);
try {
const runtime = path.join(checkout, "packages", "@rescript", "runtime");
for (const [name, generate] of Object.entries(stressInputs)) {
const file = path.join(workDir, `${name}.res`);
fs.writeFileSync(file, generate());
results[`stress/${name}.res`] = {
...measureRun(
bsc,
["-runtime-path", runtime, "-bs-no-version-header", `${name}.res`],
workDir,
instructions,
),
inputs: hashFiles([file]),
};
}
for (const name of fs.readdirSync(dataDir).sort()) {
const file = path.join(workDir, name);
fs.copyFileSync(path.join(dataDir, name), file);
const inputs = hashFiles([file]);
results[`parse/${name}`] = {
...measureRun(
bsc,
["-bs-ast", "-o", `${path.parse(name).name}.ast`, name],
workDir,
instructions,
),
inputs,
};
results[`format/${name}`] = {
...measureRun(bsc, ["-format", name], workDir, instructions),
inputs,
};
}
} finally {
fs.rmSync(workDir, { recursive: true, force: true });
}
// The outputs of the runtime and Belt, which the replayed builds wrote
// again.
for (const pkg of packages) {
const outputs = outputSizes(
path.join(checkout, pkg.dir, "lib", "rescript"),
);
for (const ext of outputExtensions) {
results[`output/${path.basename(pkg.dir)}/*${ext}`] = {
bytes: outputs[ext],
inputs: packageInputs,
};
}
}
if (playground) {
results["output/playground/compiler.js"] = {
bytes: fs.statSync(path.join(checkout, playgroundCompiler)).size,
inputs: "",
};
}
if (project) {
measureProjectBuild(checkout, project, results);
measureGeneratedProjects(checkout, results);
}
return results;
}
/**
* How many times the wall-time benchmark builds its project with each
* compiler, after one build with each that isn't counted.
*/
const timingRounds = 10;
/**
* How long one of the wall-time benchmark's builds may take, in
* milliseconds, many times as long as a build takes, so that a build that
* hangs, as it could with a deadlock in the scheduling, ends the benchmark.
*/
const timingBuildTimeout = 2 * 60 * 1000;
/**
* The wall-clock times of the wall-time benchmark's builds, in
* milliseconds, by benchmark: round i built with the base's compiler and
* the head's, one right after the other.
*
* @typedef {Record<string, { base: number[], head: number[] }>} Timings
*/
/**
* Builds the wall-time benchmark's project clean with the build systems of
* two checkouts in turn, on as many worker domains as the build system
* chooses, and returns how long each build took. The two compilers take
* turns going first, so that a machine that gets slower or faster during
* the run changes both alike.
*
* Wall-clock time on a loaded machine varies by several percent from one
* build to the next, and more over minutes, so this only indicates the
* effect of a change that counting doesn't show, such as starting a module
* earlier: building the same modules with idle domains doing less is
* faster, but allocates and executes as much or more.
*
* Each checkout builds a copy of the project of its own, with its own
* runtime, both under paths of the same length.
*
* @param {string} baseCheckout
* @param {string} headCheckout
* @param {number} rounds
* @returns {Timings}
*/
export function timeBuilds(baseCheckout, headCheckout, rounds) {
const workDir = path.join(os.tmpdir(), "compiler-bench-time");
fs.rmSync(workDir, { recursive: true, force: true });
try {
const project = chainProject();
const sides = [
{ name: "base", checkout: baseCheckout },
{ name: "head", checkout: headCheckout },
].map(side => {
const dir = path.join(workDir, side.name);
writeProject(project, dir, side.checkout);
return {
...side,
dir,
rescript: path.join(side.checkout, relativeBinDir, "rescript.exe"),
/** @type {number[]} */
times: [],
};
});
/** @param {(typeof sides)[number]} side */
const build = side => {
fs.rmSync(path.join(side.dir, "lib"), { recursive: true, force: true });
const start = process.hrtime.bigint();
execFileSync(side.rescript, ["build"], {
cwd: side.dir,
stdio: "pipe",
timeout: timingBuildTimeout,
killSignal: "SIGKILL",
});
return Number(process.hrtime.bigint() - start) / 1e6;
};
for (const side of sides) build(side);
for (let round = 0; round < rounds; round++) {
const order = round % 2 === 0 ? sides : [...sides].reverse();
for (const side of order) side.times.push(build(side));
}
return {
"time/Chain/clean": { base: sides[0].times, head: sides[1].times },
};
} finally {
fs.rmSync(workDir, { recursive: true, force: true });
}
}
/**
* The median of numbers.
*
* @param {number[]} values
*/
export function median(values) {
const sorted = [...values].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2 === 1
? sorted[middle]
: (sorted[middle - 1] + sorted[middle]) / 2;
}
/**
* A pseudo-random number generator (mulberry32), so that the confidence
* interval of the same times is the same in every run.
*
* @param {number} seed
* @returns {() => number} numbers in [0, 1)
*/
function randomNumbers(seed) {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;