|
| 1 | +/** |
| 2 | + * CPU-profiles a single benchmark scenario and prints the hottest functions |
| 3 | + * by self time. Builds unminified so function names survive. |
| 4 | + * |
| 5 | + * Usage: node profile.mjs <scenario> [--runs 3] [--skip-build] [--top 40] |
| 6 | + */ |
| 7 | +import path from "node:path"; |
| 8 | +import process from "node:process"; |
| 9 | +import { fileURLToPath } from "node:url"; |
| 10 | +import { build, preview } from "vite"; |
| 11 | +import { chromium } from "playwright"; |
| 12 | + |
| 13 | +const dirname = path.dirname(fileURLToPath(import.meta.url)); |
| 14 | +const PORT = 4518; |
| 15 | + |
| 16 | +const args = process.argv.slice(2); |
| 17 | +const scenario = args.find((a) => !a.startsWith("--")); |
| 18 | +if (!scenario) { |
| 19 | + console.error("usage: node profile.mjs <scenario>"); |
| 20 | + process.exit(1); |
| 21 | +} |
| 22 | +function argValue(flag, fallback) { |
| 23 | + const i = args.indexOf(flag); |
| 24 | + return i === -1 ? fallback : args[i + 1]; |
| 25 | +} |
| 26 | +const runs = Number(argValue("--runs", "3")); |
| 27 | +const top = Number(argValue("--top", "40")); |
| 28 | +const skipBuild = args.includes("--skip-build"); |
| 29 | + |
| 30 | +async function main() { |
| 31 | + if (!skipBuild) { |
| 32 | + console.log("building (unminified)..."); |
| 33 | + await build({ |
| 34 | + root: dirname, |
| 35 | + logLevel: "warn", |
| 36 | + build: { minify: false, sourcemap: false }, |
| 37 | + }); |
| 38 | + } |
| 39 | + const server = await preview({ |
| 40 | + root: dirname, |
| 41 | + preview: { port: PORT, strictPort: true }, |
| 42 | + }); |
| 43 | + const browser = await chromium.launch({ headless: true }); |
| 44 | + const page = await browser.newPage(); |
| 45 | + try { |
| 46 | + const cdp = await page.context().newCDPSession(page); |
| 47 | + await page.goto(`http://localhost:${PORT}/?scenario=${scenario}`, { |
| 48 | + waitUntil: "load", |
| 49 | + }); |
| 50 | + await page.waitForFunction(() => window.__ready || window.__error, null, { |
| 51 | + timeout: 60_000, |
| 52 | + }); |
| 53 | + const setupError = await page.evaluate(() => window.__error); |
| 54 | + if (setupError) throw new Error(`setup failed: ${setupError}`); |
| 55 | + |
| 56 | + const cpuThrottle = await page.evaluate(() => window.__scenario.cpuThrottle); |
| 57 | + await cdp.send("Emulation.setCPUThrottlingRate", { rate: cpuThrottle }); |
| 58 | + // warmup |
| 59 | + await page.evaluate(() => window.__scenario.run()); |
| 60 | + |
| 61 | + await cdp.send("Profiler.enable"); |
| 62 | + await cdp.send("Profiler.setSamplingInterval", { interval: 100 }); |
| 63 | + await cdp.send("Profiler.start"); |
| 64 | + const durations = []; |
| 65 | + for (let i = 0; i < runs; i++) { |
| 66 | + durations.push(await page.evaluate(() => window.__scenario.run())); |
| 67 | + } |
| 68 | + const { profile } = await cdp.send("Profiler.stop"); |
| 69 | + await cdp.send("Emulation.setCPUThrottlingRate", { rate: 1 }); |
| 70 | + |
| 71 | + // aggregate self time per function |
| 72 | + const totalHits = profile.nodes.reduce((a, n) => a + (n.hitCount ?? 0), 0); |
| 73 | + const totalMs = (profile.endTime - profile.startTime) / 1000; |
| 74 | + const byFn = new Map(); |
| 75 | + for (const node of profile.nodes) { |
| 76 | + const hits = node.hitCount ?? 0; |
| 77 | + if (!hits) continue; |
| 78 | + const cf = node.callFrame; |
| 79 | + const url = cf.url.replace(/^https?:\/\/[^/]+/, "").split("?")[0]; |
| 80 | + const key = `${cf.functionName || "(anonymous)"} ${url}:${cf.lineNumber + 1}`; |
| 81 | + byFn.set(key, (byFn.get(key) ?? 0) + hits); |
| 82 | + } |
| 83 | + const rows = [...byFn.entries()] |
| 84 | + .map(([key, hits]) => ({ key, hits, ms: (hits / totalHits) * totalMs })) |
| 85 | + .sort((a, b) => b.hits - a.hits) |
| 86 | + .slice(0, top); |
| 87 | + |
| 88 | + console.log( |
| 89 | + `\nscenario=${scenario} cpu=${cpuThrottle}x runs=${runs} run-durations=[${durations.map((d) => d.toFixed(1)).join(", ")}]ms` |
| 90 | + ); |
| 91 | + console.log(`profile wall time ${totalMs.toFixed(0)}ms, ${totalHits} samples\n`); |
| 92 | + console.log(`${"self-ms".padEnd(10)}${"self-%".padEnd(9)}function`); |
| 93 | + for (const r of rows) { |
| 94 | + const pct = ((r.hits / totalHits) * 100).toFixed(1); |
| 95 | + console.log(`${r.ms.toFixed(1).padEnd(10)}${`${pct}%`.padEnd(9)}${r.key}`); |
| 96 | + } |
| 97 | + } finally { |
| 98 | + await browser.close(); |
| 99 | + await new Promise((resolve) => server.httpServer.close(resolve)); |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +main().catch((e) => { |
| 104 | + console.error(e); |
| 105 | + process.exit(1); |
| 106 | +}); |
0 commit comments