|
1 | 1 | 'use strict' |
2 | 2 |
|
3 | | -const { spawn } = require('child_process') |
| 3 | +// Measures the working tree against another revision, with the noise of this machine beside it. |
| 4 | +// |
| 5 | +// Each benchmark runs in four workers at once, two on the other revision (A) and two on the working |
| 6 | +// tree (B), and they take turns in batches of about 10ms, so a machine that warms up or throttles |
| 7 | +// slows all four together. A against A and B against B is the same code against itself: how far it |
| 8 | +// moves is the noise, printed as "noise A" and "noise B". "B vs A" is positive when the working tree |
| 9 | +// is faster, and it is followed by the band that noise gives to it: outside the band the row is |
| 10 | +// faster or slower, by at least what is left of B vs A once the band is taken off. |
| 11 | +// |
| 12 | +// npm run bench:cmp main against the working tree |
| 13 | +// npm run bench:cmp -- --against v7.0.0 |
| 14 | +// npm run bench:cmp -- --only "short string" --sessions 10 |
| 15 | +// npm run bench:cmp -- --min-effect 0.5 report what is over the band by 0.5%, 1% when not given |
| 16 | +// |
| 17 | +// On a clean tree, --against HEAD puts the same code on both sides and every row should be noise. |
| 18 | + |
| 19 | +const { Worker, isMainThread, workerData, parentPort } = require('node:worker_threads') |
| 20 | +const { execFileSync } = require('node:child_process') |
| 21 | +const { once } = require('node:events') |
| 22 | +const { parseArgs } = require('node:util') |
| 23 | +const fs = require('node:fs') |
| 24 | +const path = require('node:path') |
| 25 | +const v8 = require('node:v8') |
| 26 | + |
| 27 | +const ROOT = path.join(__dirname, '..') |
| 28 | +// inside the repo, so the other revision resolves node_modules from here |
| 29 | +const WORKTREE = path.join(ROOT, '.bench-worktree') |
| 30 | +const WARMUP_MS = 250 |
| 31 | +const BATCH_NS = 1e7 |
| 32 | +// how many standard errors A/B has to be from zero: with 5 sessions, about 1 row in 400 of the |
| 33 | +// same code against itself |
| 34 | +const BAND = 4 |
| 35 | + |
| 36 | +// the four workers are a1 a2 b1 b2; turning through these orders keeps a drift of the machine out |
| 37 | +// of A/B in every round, and out of A/A and B/B every four rounds |
| 38 | +const ORDERS = [[0, 2, 3, 1], [2, 0, 1, 3], [1, 3, 2, 0], [3, 1, 0, 2]] |
4 | 39 |
|
5 | | -const cliSelect = require('cli-select') |
6 | | -const simpleGit = require('simple-git') |
7 | | - |
8 | | -const git = simpleGit(process.cwd()) |
9 | | - |
10 | | -const COMMAND = 'npm run bench' |
11 | | -const DEFAULT_BRANCH = 'main' |
12 | | -const PERCENT_THRESHOLD = 5 |
13 | | -const greyColor = '\x1b[30m' |
14 | | -const redColor = '\x1b[31m' |
15 | 40 | const greenColor = '\x1b[32m' |
| 41 | +const redColor = '\x1b[31m' |
16 | 42 | const resetColor = '\x1b[0m' |
17 | 43 |
|
18 | | -async function selectBranchName (message, branches) { |
19 | | - console.log(message) |
20 | | - const result = await cliSelect({ |
21 | | - type: 'list', |
22 | | - name: 'branch', |
23 | | - values: branches |
| 44 | +if (isMainThread) { |
| 45 | + main().catch((error) => { |
| 46 | + console.error(error) |
| 47 | + removeWorktree() |
| 48 | + process.exitCode = 1 |
24 | 49 | }) |
25 | | - console.log(result.value) |
26 | | - return result.value |
| 50 | +} else { |
| 51 | + arm() |
27 | 52 | } |
28 | 53 |
|
29 | | -async function executeCommandOnBranch (command, branch) { |
30 | | - console.log(`${greyColor}Checking out "${branch}"${resetColor}`) |
31 | | - await git.checkout(branch) |
| 54 | +// One side: builds the serializer of a benchmark, then warms it up or runs a batch when asked |
| 55 | +function arm () { |
| 56 | + const build = require(workerData.lib) |
| 57 | + const { schema, options, input, compile } = require('./bench.js')[workerData.index] |
| 58 | + const stringify = compile ? null : build(schema, options) |
| 59 | + // the input at an index that changes and the last two results kept, so V8 can neither write the |
| 60 | + // string once outside the loop nor drop the call; more results kept put the GC in the measure |
| 61 | + const inputs = [input, input] |
| 62 | + const results = [null, null] |
| 63 | + |
| 64 | + function batch (calls) { |
| 65 | + const start = process.hrtime.bigint() |
| 66 | + if (compile) { |
| 67 | + for (let i = 0; i < calls; i++) results[i & 1] = build(schema, options)(inputs[i & 1]) |
| 68 | + } else { |
| 69 | + for (let i = 0; i < calls; i++) results[i & 1] = stringify(inputs[i & 1]) |
| 70 | + } |
| 71 | + return Number(process.hrtime.bigint() - start) |
| 72 | + } |
32 | 73 |
|
33 | | - console.log(`${greyColor}Execute "${command}"${resetColor}`) |
34 | | - const childProcess = spawn(command, { stdio: 'pipe', shell: true }) |
| 74 | + // answers how many calls fill a batch |
| 75 | + function warmup (ms) { |
| 76 | + let calls = 1 |
| 77 | + const end = Date.now() + ms |
| 78 | + while (Date.now() < end) { |
| 79 | + if (batch(calls) < BATCH_NS) calls *= 2 |
| 80 | + } |
| 81 | + return Math.max(1, Math.round(calls * BATCH_NS / batch(calls))) |
| 82 | + } |
35 | 83 |
|
36 | | - let result = '' |
37 | | - childProcess.stdout.on('data', (data) => { |
38 | | - process.stdout.write(data.toString()) |
39 | | - result += data.toString() |
| 84 | + parentPort.on('message', ({ ms, calls }) => { |
| 85 | + parentPort.postMessage(ms ? warmup(ms) : Math.log(calls * 1e9 / batch(calls))) |
40 | 86 | }) |
| 87 | +} |
41 | 88 |
|
42 | | - await new Promise(resolve => childProcess.on('close', resolve)) |
43 | | - |
44 | | - console.log() |
45 | | - |
46 | | - return parseBenchmarksStdout(result) |
| 89 | +function median (values) { |
| 90 | + const sorted = [...values].sort((a, b) => a - b) |
| 91 | + return sorted[sorted.length >> 1] |
47 | 92 | } |
48 | 93 |
|
49 | | -function parseBenchmarksStdout (text) { |
50 | | - const results = [] |
| 94 | +async function ask (worker, message) { |
| 95 | + const answer = once(worker, 'message') |
| 96 | + worker.postMessage(message) |
| 97 | + return (await answer)[0] |
| 98 | +} |
51 | 99 |
|
52 | | - const lines = text.split('\n') |
53 | | - for (const line of lines) { |
54 | | - const match = /^(.+?)(\.*) x (.+) ops\/sec .*$/.exec(line) |
55 | | - if (match !== null) { |
56 | | - results.push({ |
57 | | - name: match[1], |
58 | | - alignedName: match[1] + match[2], |
59 | | - result: parseInt(match[3].split(',').join('')) |
60 | | - }) |
| 100 | +// Four fresh workers taking turns batch by batch. Answers, in logs and as medians over the rounds, |
| 101 | +// B against A, A2 against A1 and B2 against B1 |
| 102 | +async function session (libs, index, rounds, number) { |
| 103 | + // started and warmed up one at a time, as A B B A or B A A B, so no side is always first: |
| 104 | + // warming up four together spread them further apart |
| 105 | + const start = ORDERS[number % 2] |
| 106 | + const workers = [] |
| 107 | + for (const i of start) workers[i] = new Worker(__filename, { workerData: { lib: libs[i], index } }) |
| 108 | + try { |
| 109 | + const calls = [] |
| 110 | + for (const i of start) calls[i] = await ask(workers[i], { ms: WARMUP_MS }) |
| 111 | + |
| 112 | + const ab = [] |
| 113 | + const aa = [] |
| 114 | + const bb = [] |
| 115 | + for (let round = 0; round < rounds; round++) { |
| 116 | + const rate = [] |
| 117 | + for (const i of ORDERS[round % ORDERS.length]) rate[i] = await ask(workers[i], { calls: calls[i] }) |
| 118 | + const [a1, a2, b1, b2] = rate |
| 119 | + ab.push((b1 + b2 - a1 - a2) / 2) |
| 120 | + aa.push(a2 - a1) |
| 121 | + bb.push(b2 - b1) |
61 | 122 | } |
| 123 | + return { ab: median(ab), aa: median(aa), bb: median(bb) } |
| 124 | + } finally { |
| 125 | + await Promise.all(workers.map((worker) => worker.terminate())) |
62 | 126 | } |
| 127 | +} |
63 | 128 |
|
64 | | - return results |
| 129 | +// A/B is the mean over the sessions, and its band comes from A/A and B/B: under the same code the |
| 130 | +// four workers are alike, so A/B spreads as much as A/A and B/B together, halved |
| 131 | +async function compare (libs, index, sessions, rounds, minEffect) { |
| 132 | + const results = [] |
| 133 | + for (let i = 0; i < sessions; i++) results.push(await session(libs, index, rounds, i)) |
| 134 | + |
| 135 | + const spread = (key) => Math.sqrt(results.reduce((sum, result) => sum + result[key] ** 2, 0) / sessions) |
| 136 | + const aa = spread('aa') |
| 137 | + const bb = spread('bb') |
| 138 | + const ab = results.reduce((sum, result) => sum + result.ab, 0) / sessions |
| 139 | + const band = BAND * Math.sqrt((aa ** 2 + bb ** 2) / 4 / sessions) |
| 140 | + // what is left of A/B once the band is taken off has to be over this, or the row is noise: the |
| 141 | + // band is the noise the four workers share, and on a row that hardly moves it gets narrower than |
| 142 | + // a small offset between the two sides |
| 143 | + const floor = Math.log1p(minEffect / 100) |
| 144 | + const verdict = Math.abs(ab) <= band + floor ? 'noise' : ab > 0 ? 'faster' : 'slower' |
| 145 | + return { aa, bb, ab, band, verdict } |
65 | 146 | } |
66 | 147 |
|
67 | | -function compareResults (featureBranch, mainBranch) { |
68 | | - for (const { name, alignedName, result: mainBranchResult } of mainBranch) { |
69 | | - const featureBranchBenchmark = featureBranch.find(result => result.name === name) |
70 | | - if (featureBranchBenchmark) { |
71 | | - const featureBranchResult = featureBranchBenchmark.result |
72 | | - const percent = (featureBranchResult - mainBranchResult) * 100 / mainBranchResult |
73 | | - const roundedPercent = Math.round(percent * 100) / 100 |
74 | | - |
75 | | - const percentString = roundedPercent > 0 ? `+${roundedPercent}%` : `${roundedPercent}%` |
76 | | - const message = alignedName + percentString.padStart(7, '.') |
77 | | - |
78 | | - if (roundedPercent > PERCENT_THRESHOLD) { |
79 | | - console.log(`${greenColor}${message}${resetColor}`) |
80 | | - } else if (roundedPercent < -PERCENT_THRESHOLD) { |
81 | | - console.log(`${redColor}${message}${resetColor}`) |
82 | | - } else { |
83 | | - console.log(message) |
84 | | - } |
| 148 | +function git (...args) { |
| 149 | + return execFileSync('git', args, { cwd: ROOT, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) |
| 150 | +} |
| 151 | + |
| 152 | +function removeWorktree () { |
| 153 | + if (fs.existsSync(WORKTREE)) { |
| 154 | + try { |
| 155 | + git('worktree', 'remove', '--force', WORKTREE) |
| 156 | + } catch { |
| 157 | + fs.rmSync(WORKTREE, { recursive: true, force: true }) |
85 | 158 | } |
86 | 159 | } |
| 160 | + git('worktree', 'prune') |
87 | 161 | } |
88 | 162 |
|
89 | | -(async function () { |
90 | | - const branches = await git.branch() |
91 | | - const currentBranch = branches.branches[branches.current] |
92 | | - |
93 | | - let featureBranch = null |
94 | | - let mainBranch = null |
95 | | - |
96 | | - if (process.argv[2] === '--ci') { |
97 | | - featureBranch = currentBranch.name |
98 | | - mainBranch = DEFAULT_BRANCH |
99 | | - } else { |
100 | | - featureBranch = await selectBranchName('Select the branch you want to compare (feature branch):', branches.all) |
101 | | - mainBranch = await selectBranchName('Select the branch you want to compare with (main branch):', branches.all) |
| 163 | +// a log of a ratio, as a percentage |
| 164 | +const percent = (log) => (Math.expm1(log) * 100).toFixed(1) + '%' |
| 165 | + |
| 166 | +async function main () { |
| 167 | + const { values } = parseArgs({ |
| 168 | + options: { |
| 169 | + against: { type: 'string', default: 'main' }, |
| 170 | + only: { type: 'string' }, |
| 171 | + sessions: { type: 'string', default: '5' }, |
| 172 | + rounds: { type: 'string', default: '20' }, |
| 173 | + 'min-effect': { type: 'string', default: '1' } |
| 174 | + } |
| 175 | + }) |
| 176 | + // every worker with the young generation at its largest, or it grows with what the build allocated |
| 177 | + // and a branch whose build allocates more runs the same code with fewer GCs |
| 178 | + v8.setFlagsFromString('--min-semi-space-size=16') |
| 179 | + |
| 180 | + const sessions = Number(values.sessions) |
| 181 | + const rounds = Number(values.rounds) |
| 182 | + for (const [name, value] of [['sessions', sessions], ['rounds', rounds]]) { |
| 183 | + if (!Number.isInteger(value) || value < 1) throw new Error(`--${name} must be a positive integer`) |
102 | 184 | } |
103 | 185 |
|
| 186 | + const minEffect = Number(values['min-effect']) |
| 187 | + if (!(minEffect >= 0)) throw new Error('--min-effect must be a percentage, 0 or more') |
| 188 | + |
| 189 | + const benchmarks = require('./bench.js') |
| 190 | + const selected = benchmarks |
| 191 | + .map((benchmark, index) => ({ name: benchmark.name, index })) |
| 192 | + .filter(({ name }) => !values.only || name.includes(values.only)) |
| 193 | + if (selected.length === 0) throw new Error(`no benchmark has "${values.only}" in its name`) |
| 194 | + const width = Math.max(...selected.map(({ name }) => name.length)) + 2 |
| 195 | + // one row of the table: the name, dots up to the columns, then the four numbers to the right of them |
| 196 | + const row = (name, ...cells) => name.padEnd(width, name ? '.' : ' ') + cells.map((cell) => cell.padStart(10)).join('') |
| 197 | + |
| 198 | + removeWorktree() |
| 199 | + git('worktree', 'add', '--detach', WORKTREE, values.against) |
| 200 | + const libs = [WORKTREE, WORKTREE, ROOT, ROOT] |
| 201 | + |
| 202 | + console.log(`${values.against} (A) against the working tree (B), ${sessions} sessions of ${rounds} rounds\n`) |
| 203 | + console.log('Columns:') |
| 204 | + console.log(' noise A, noise B the same code against itself: how far this machine moves it') |
| 205 | + console.log(' B vs A positive when the working tree is faster') |
| 206 | + console.log(' band what the noise alone gives to B vs A: inside it the row is noise') |
| 207 | + console.log(` result faster or slower when B vs A is outside the band by more than ${minEffect}%\n`) |
| 208 | + const counts = { faster: 0, slower: 0, noise: 0, failed: 0 } |
| 209 | + // the titles of the columns come with the first row, not alone while it is being measured |
| 210 | + let titles = row('', 'noise A', 'noise B', 'B vs A', 'band') + ' result\n' |
| 211 | + const print = (line) => { |
| 212 | + console.log(titles + line) |
| 213 | + titles = '' |
| 214 | + } |
104 | 215 | try { |
105 | | - const featureBranchResult = await executeCommandOnBranch(COMMAND, featureBranch) |
106 | | - const mainBranchResult = await executeCommandOnBranch(COMMAND, mainBranch) |
107 | | - compareResults(featureBranchResult, mainBranchResult) |
108 | | - } catch (error) { |
109 | | - console.error('Switch to origin branch due to an error', error.message) |
| 216 | + for (const { name, index } of selected) { |
| 217 | + try { |
| 218 | + const { aa, bb, ab, band, verdict } = await compare(libs, index, sessions, rounds, minEffect) |
| 219 | + counts[verdict]++ |
| 220 | + const sign = ab > 0 ? '+' : '' |
| 221 | + // B vs A with the band taken off: the part of it the noise cannot explain |
| 222 | + const net = Math.abs(Math.expm1(ab - Math.sign(ab) * band)) * 100 |
| 223 | + const result = verdict === 'noise' ? verdict : `${verdict} by at least ${net.toFixed(1)}%` |
| 224 | + const line = row(name, '±' + percent(aa), '±' + percent(bb), sign + percent(ab), '±' + percent(band)) + |
| 225 | + ' ' + result |
| 226 | + const color = verdict === 'faster' ? greenColor : verdict === 'slower' ? redColor : '' |
| 227 | + print(color ? `${color}${line}${resetColor}` : line) |
| 228 | + } catch (error) { |
| 229 | + counts.failed++ |
| 230 | + print(`${name.padEnd(width, '.')} failed: ${error.message}`) |
| 231 | + } |
| 232 | + } |
| 233 | + } finally { |
| 234 | + removeWorktree() |
110 | 235 | } |
111 | 236 |
|
112 | | - await git.checkout(currentBranch.commit) |
113 | | - await git.checkout(currentBranch.name) |
114 | | - |
115 | | - console.log(`${greyColor}Back to ${currentBranch.name} ${currentBranch.commit}${resetColor}`) |
116 | | -})() |
| 237 | + console.log(`\n${counts.faster} faster, ${counts.slower} slower, ${counts.noise} within the noise` + |
| 238 | + (counts.failed ? `, ${counts.failed} failed` : '')) |
| 239 | +} |
0 commit comments