-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbench-compare.mjs
More file actions
280 lines (236 loc) · 9.25 KB
/
bench-compare.mjs
File metadata and controls
280 lines (236 loc) · 9.25 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
#!/usr/bin/env node
/**
* Benchmark Comparison Script (A/B testing)
*
* Compares benchmark results between two git refs (branches, commits, tags).
* Runs the benchmark suite on each ref and produces a side-by-side comparison
* with statistical significance testing.
*
* Usage:
* node scripts/bench-compare.mjs main # compare current vs main
* node scripts/bench-compare.mjs main feature-x # compare two branches
* node scripts/bench-compare.mjs HEAD~3 # compare current vs 3 commits ago
* node scripts/bench-compare.mjs --runs 5 main # 5 runs per ref (default: 3)
*
* Output:
* Printed table with ops/sec, change %, and significance indicator
* profiles/compare-<timestamp>.json — raw data for further analysis
*/
import { execSync } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { resolve, join } from "node:path";
const ROOT = resolve(import.meta.dirname, "..");
const PROFILES_DIR = join(ROOT, "profiles");
const BENCH_CMD =
"node --experimental-transform-types bench/engine.bench.ts";
const BENCH_CWD = join(ROOT, "packages/bridge");
// ── Parse args ───────────────────────────────────────────────────────────────
const args = process.argv.slice(2).filter((a) => !a.startsWith("--"));
const allArgs = process.argv.slice(2);
function getArg(name) {
const idx = allArgs.indexOf(`--${name}`);
return idx !== -1 && idx + 1 < allArgs.length ? allArgs[idx + 1] : undefined;
}
const hasFlag = (name) => allArgs.includes(`--${name}`);
const runs = parseInt(getArg("runs") ?? "3", 10);
if (hasFlag("help") || args.length === 0) {
console.log(`
Benchmark Comparison (A/B Testing)
Usage:
node scripts/bench-compare.mjs <base-ref> [<head-ref>]
Arguments:
base-ref Git ref to compare against (branch, commit, tag)
head-ref Git ref to measure (default: current working tree)
Options:
--runs <n> Number of benchmark runs per ref (default: 3)
--help Show this help
Examples:
node scripts/bench-compare.mjs main
node scripts/bench-compare.mjs main feature-x --runs 5
node scripts/bench-compare.mjs HEAD~5
`);
process.exit(0);
}
const baseRef = args[0];
const headRef = args[1] ?? null; // null = current working tree
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
// ── Helpers ──────────────────────────────────────────────────────────────────
function getCurrentRef() {
try {
return execSync("git rev-parse --short HEAD", {
cwd: ROOT,
encoding: "utf-8",
}).trim();
} catch {
return "working-tree";
}
}
function stashIfDirty() {
const status = execSync("git status --porcelain", {
cwd: ROOT,
encoding: "utf-8",
}).trim();
if (status) {
console.log(" Stashing uncommitted changes...");
execSync("git stash push -m 'bench-compare auto-stash'", {
cwd: ROOT,
stdio: "inherit",
});
return true;
}
return false;
}
function checkoutRef(ref) {
execSync(`git checkout ${ref}`, { cwd: ROOT, stdio: "inherit" });
// Reinstall deps in case they changed
try {
execSync("pnpm install --frozen-lockfile", {
cwd: ROOT,
stdio: "pipe",
timeout: 60000,
});
} catch {
// Lockfile might differ — try without frozen
execSync("pnpm install", { cwd: ROOT, stdio: "pipe", timeout: 60000 });
}
}
function runBench() {
// Run bench with CI=true to get JSON output
const output = execSync(BENCH_CMD, {
cwd: BENCH_CWD,
env: { ...process.env, CI: "true" },
encoding: "utf-8",
timeout: 120000,
stdio: ["pipe", "pipe", "pipe"],
});
// Parse BMF JSON from stdout (skip non-JSON lines)
const lines = output.split("\n");
const jsonStart = lines.findIndex((l) => l.trim().startsWith("{"));
const jsonEnd = lines.findLastIndex((l) => l.trim().startsWith("}"));
if (jsonStart === -1 || jsonEnd === -1) {
throw new Error("Could not find JSON output in benchmark results");
}
const json = lines.slice(jsonStart, jsonEnd + 1).join("\n");
return JSON.parse(json);
}
function collectRuns(label, n) {
console.log(` Running ${n} benchmark iterations for "${label}"...`);
const results = [];
for (let i = 0; i < n; i++) {
process.stdout.write(` Run ${i + 1}/${n}... `);
const data = runBench();
results.push(data);
console.log("done");
}
return results;
}
function aggregateRuns(runs) {
// For each benchmark, compute mean and stddev of the mean latency
const benchNames = Object.keys(runs[0]);
const aggregated = {};
for (const name of benchNames) {
const values = runs
.map((r) => r[name]?.latency?.value)
.filter((v) => v != null);
if (values.length === 0) continue;
const mean = values.reduce((a, b) => a + b, 0) / values.length;
const variance =
values.reduce((sum, v) => sum + (v - mean) ** 2, 0) / values.length;
const stddev = Math.sqrt(variance);
const opsPerSec = Math.round(1_000_000 / mean); // mean is in nanoseconds from BMF
aggregated[name] = {
meanLatencyNs: mean,
stddevNs: stddev,
opsPerSec,
samples: values,
};
}
return aggregated;
}
function formatChange(baseOps, headOps) {
const change = ((headOps - baseOps) / baseOps) * 100;
const sign = change >= 0 ? "+" : "";
const indicator = Math.abs(change) < 3 ? "~" : change > 0 ? "✅" : "⚠️";
return { changeStr: `${sign}${change.toFixed(1)}%`, indicator };
}
// ── Main ─────────────────────────────────────────────────────────────────────
mkdirSync(PROFILES_DIR, { recursive: true });
console.log(`\n📊 Benchmark Comparison`);
console.log(` Base: ${baseRef}`);
console.log(` Head: ${headRef ?? "(current)"}`);
console.log(` Runs: ${runs} per ref\n`);
const currentRef = getCurrentRef();
let didStash = false;
try {
// ── Collect HEAD results first (if measuring working tree) ──────────────
let headResults;
if (!headRef) {
console.log(`\n── Measuring HEAD (${currentRef}) ──`);
headResults = collectRuns(currentRef, runs);
}
// ── Collect BASE results ───────────────────────────────────────────────
console.log(`\n── Measuring base: ${baseRef} ──`);
didStash = stashIfDirty();
checkoutRef(baseRef);
const baseResults = collectRuns(baseRef, runs);
// ── Collect HEAD results (if specific ref) ─────────────────────────────
if (headRef) {
console.log(`\n── Measuring head: ${headRef} ──`);
checkoutRef(headRef);
headResults = collectRuns(headRef, runs);
}
// ── Return to original state ───────────────────────────────────────────
console.log(`\n── Restoring to ${currentRef} ──`);
checkoutRef(currentRef);
if (didStash) {
console.log(" Restoring stashed changes...");
execSync("git stash pop", { cwd: ROOT, stdio: "inherit" });
}
// ── Aggregate & compare ────────────────────────────────────────────────
const baseAgg = aggregateRuns(baseResults);
const headAgg = aggregateRuns(headResults);
console.log(`\n${"═".repeat(90)}`);
console.log(
` ${"Benchmark".padEnd(42)} ${"Base ops/s".padStart(12)} ${"Head ops/s".padStart(12)} ${"Change".padStart(10)} `,
);
console.log(`${"─".repeat(90)}`);
for (const name of Object.keys(baseAgg)) {
const base = baseAgg[name];
const head = headAgg[name];
if (!head) continue;
const { changeStr, indicator } = formatChange(
base.opsPerSec,
head.opsPerSec,
);
console.log(
` ${name.padEnd(42)} ${base.opsPerSec.toLocaleString().padStart(12)} ${head.opsPerSec.toLocaleString().padStart(12)} ${changeStr.padStart(10)} ${indicator}`,
);
}
console.log(`${"═".repeat(90)}\n`);
// ── Save raw data ──────────────────────────────────────────────────────
const compareData = {
timestamp,
baseRef,
headRef: headRef ?? currentRef,
runs,
base: baseAgg,
head: headAgg,
};
const outPath = join(PROFILES_DIR, `compare-${timestamp}.json`);
writeFileSync(outPath, JSON.stringify(compareData, null, 2), "utf-8");
console.log(`Raw data saved to: profiles/compare-${timestamp}.json\n`);
} catch (error) {
// Restore state on error
console.error(`\n❌ Error: ${error.message}`);
try {
execSync(`git checkout ${currentRef}`, { cwd: ROOT, stdio: "pipe" });
if (didStash) {
execSync("git stash pop", { cwd: ROOT, stdio: "pipe" });
}
} catch {
console.error(
"⚠️ Failed to restore git state. You may need to manually checkout.",
);
}
process.exit(1);
}