Skip to content

Commit c68570d

Browse files
nigrosimoneTony133
andauthored
chore(benchmark): compare branches against the noise of the same code (#888)
`npm run bench:cmp` now runs each benchmark in four workers, two on the other revision and two on the working tree, taking turns in short batches. The same code against itself gives the noise of the machine, and a row is reported as faster or slower only when it is outside that band by more than `--min-effect` (1% by default). The old script used a fixed 5% threshold. The other revision is checked out in a temporary git worktree, so the working copy is no longer switched between branches. This removes `simple-git` and `cli-select`, and fixes `bench:cmp`, broken since #891. The `bench:cmp:ci` script is removed. The output is a table with a short legend, and `--sessions`, `--rounds` and `--only` are checked. The "short array of long strings" row now uses the long strings. Co-authored-by: Antonio Tripodi <Tony133@users.noreply.github.com>
1 parent e10a3e0 commit c68570d

4 files changed

Lines changed: 219 additions & 91 deletions

File tree

‎.gitignore‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,3 +152,6 @@ yarn.lock
152152
.pi
153153
AGENTS.md
154154
CLAUDE.md
155+
156+
# the other revision benchmark/bench-cmp-branch.js measures against
157+
.bench-worktree

‎benchmark/bench-cmp-branch.js‎

Lines changed: 209 additions & 86 deletions
Original file line numberDiff line numberDiff line change
@@ -1,116 +1,239 @@
11
'use strict'
22

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]]
439

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'
1540
const greenColor = '\x1b[32m'
41+
const redColor = '\x1b[31m'
1642
const resetColor = '\x1b[0m'
1743

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
2449
})
25-
console.log(result.value)
26-
return result.value
50+
} else {
51+
arm()
2752
}
2853

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+
}
3273

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+
}
3583

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)))
4086
})
87+
}
4188

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]
4792
}
4893

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+
}
5199

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)
61122
}
123+
return { ab: median(ab), aa: median(aa), bb: median(bb) }
124+
} finally {
125+
await Promise.all(workers.map((worker) => worker.terminate()))
62126
}
127+
}
63128

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 }
65146
}
66147

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 })
85158
}
86159
}
160+
git('worktree', 'prune')
87161
}
88162

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`)
102184
}
103185

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+
}
104215
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()
110235
}
111236

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+
}

‎benchmark/bench.js‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ const benchmarks = [
180180
type: 'array',
181181
items: { type: 'string' }
182182
},
183-
input: shortArrayOfShortStrings
183+
input: shortArrayOfLongStrings
184184
},
185185
{
186186
name: 'short array of objects with properties of different types',
@@ -598,4 +598,9 @@ async function runBenchmarks () {
598598
}
599599
}
600600

601-
runBenchmarks()
601+
// bench-cmp-branch.js runs the same cases
602+
module.exports = benchmarks
603+
604+
if (require.main === module) {
605+
runBenchmarks()
606+
}

‎package.json‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
"scripts": {
99
"bench": "node --expose-gc ./benchmark/bench.js",
1010
"bench:cmp": "node ./benchmark/bench-cmp-branch.js",
11-
"bench:cmp:ci": "node ./benchmark/bench-cmp-branch.js --ci",
1211
"benchmark": "node --expose-gc ./benchmark/bench-cmp-lib.js",
1312
"lint": "eslint",
1413
"lint:fix": "eslint --fix",
@@ -63,13 +62,11 @@
6362
],
6463
"devDependencies": {
6564
"c8": "^12.0.0",
66-
"cli-select": "^1.1.2",
6765
"compile-json-stringify": "^0.1.2",
6866
"eslint": "^9.39.2",
6967
"fast-json-stringify": ".",
7068
"json-accelerator": "^0.1.7",
7169
"neostandard": "^0.13.0",
72-
"simple-git": "^4.0.2",
7370
"tinybench": "^6.0.0",
7471
"tstyche": "^7.1.0",
7572
"typebox": "^1.0.81",

0 commit comments

Comments
 (0)