Performance benchmark on a big network, posted on every PR
scripts/perf-bench.js times routing, a game day, an action, panels, the NOC dashboard and the map on tests/fixtures/big-network.json (104 POPs, 950 PNIs, 832 caches), base and head in alternating turns, and says whether routing results changed. perf.yml runs it on every PR against the base; perf-comment.yml posts the table as one updated comment. New performance skill, CLAUDE.md rule, PR template and docs.
This commit is contained in:
parent
ad8b1bebcb
commit
308c3f7045
13 changed files with 322 additions and 1 deletions
92
scripts/perf-bench.js
Normal file
92
scripts/perf-bench.js
Normal file
|
|
@ -0,0 +1,92 @@
|
|||
#!/usr/bin/env node
|
||||
// Performance benchmark on a very large network (tests/fixtures/big-network.json).
|
||||
//
|
||||
// node scripts/perf-bench.js time this checkout
|
||||
// node scripts/perf-bench.js --base OLD.html compare OLD.html (e.g. main) with this checkout
|
||||
// node scripts/perf-bench.js --base OLD.html --md out.md --summary "$GITHUB_STEP_SUMMARY"
|
||||
//
|
||||
// Both versions load the same save in one process and are timed in alternating turns, so a busy machine slows
|
||||
// them equally. Each number is the median of several runs. It also says whether both versions route the save's
|
||||
// traffic identically, which catches unintended gameplay changes in a "pure speed" PR.
|
||||
// Headless (jsdom, a recording canvas): it measures our JavaScript, not the browser's painting.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('../tests/harness');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const HEAD = opt('--head', path.join(ROOT, 'site', 'index.html'));
|
||||
const BASE = opt('--base', null);
|
||||
const RUNS = +opt('--runs', 7);
|
||||
const SAVE = fs.readFileSync(opt('--save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json')), 'utf8');
|
||||
|
||||
// What we time. Each body runs inside the game page; panels flip between two selections so nothing can be
|
||||
// skipped as "unchanged".
|
||||
const METRICS = [
|
||||
['compute', 'Routing: compute()', 'compute()'],
|
||||
['day', 'One game day: dayTick()', 'S.nextFail=S.day+99;S.nextEvent=S.day+99;dayTick()'],
|
||||
['action', 'An action: after()', 'after()'],
|
||||
['panels', 'Side panel and left list', "__flip=!__flip;UI.sel={type:'city',id:__flip?'fra':'ams'};UI.tab=__flip?'peer':'up';UI.left=__flip?'nets':'noc';UI.leftOpen=true;renderPanel();renderLeft()"],
|
||||
['dash', 'NOC dashboard tabs', "$('dash').hidden=false;for(const k of ['overview','conn','traffic','infra','cust']){UI.dtab=k;renderDash();}$('dash').hidden=true"],
|
||||
['map', 'Map at three zoom levels', "for(const z of [1,3.2,7]){cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=z;draw(0);}"],
|
||||
];
|
||||
|
||||
function open(file) {
|
||||
const { ev, errors } = load({ file, seed: 777 });
|
||||
ev(`window.__flip=false;S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();renderAll();`);
|
||||
const time = (body) => ev(`(()=>{const t=performance.now();${body};return performance.now()-t;})()`);
|
||||
// What the network carries, to tell a pure speed-up from a change in how traffic is routed.
|
||||
const outcome = () => ev(`(()=>{compute();const r=[R.served,R.demand,R.reach,R.peered,JSON.stringify(R.egT),...Object.keys(R.citySrv).sort().map(c=>R.citySrv[c]),...S.links.map(l=>R.load[l.id]||0)];
|
||||
return r.map(x=>typeof x==='number'?x.toFixed(6):x).join('|');})()`);
|
||||
const size = JSON.parse(ev("JSON.stringify({pops:Object.keys(S.pops).length,links:S.links.length,pni:S.pni.length,caches:S.caches.length,customers:S.biz.length,ix:Object.keys(S.ixp).length})"));
|
||||
return { ev, errors, time, outcome, size };
|
||||
}
|
||||
|
||||
const median = (a) => { const s = [...a].sort((x, y) => x - y); return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2; };
|
||||
const ms = (x) => x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2);
|
||||
|
||||
const head = open(HEAD), base = BASE ? open(BASE) : null;
|
||||
const sameOutcome = base ? base.outcome() === head.outcome() : null;
|
||||
const res = {};
|
||||
for (const [k, , body] of METRICS) {
|
||||
const h = [], b = [];
|
||||
for (const v of [head, base].filter(Boolean)) { v.time(body); v.time(body); } // warm up
|
||||
for (let i = 0; i < RUNS; i++) {
|
||||
// Alternate who goes first, so drift over the run lands on both sides.
|
||||
if (base && i % 2) { b.push(base.time(body)); h.push(head.time(body)); } else { h.push(head.time(body)); if (base) b.push(base.time(body)); }
|
||||
}
|
||||
res[k] = { head: median(h), base: base ? median(b) : null };
|
||||
}
|
||||
const errs = [...head.errors, ...(base ? base.errors : [])];
|
||||
|
||||
// Verdicts: small absolute differences are noise, whatever the percentage.
|
||||
const verdict = (r) => {
|
||||
if (r.base == null) return '';
|
||||
const ratio = r.head / (r.base || 1e-9), diff = r.head - r.base;
|
||||
if (Math.abs(diff) < 2) return '≈';
|
||||
if (ratio >= 1.5) return '🔴 slower';
|
||||
if (ratio >= 1.15) return '⚠️ slower';
|
||||
if (ratio <= 0.85) return '🟢 faster';
|
||||
return '≈';
|
||||
};
|
||||
const pct = (r) => r.base == null ? '' : `${r.head >= r.base ? '+' : ''}${(((r.head - r.base) / (r.base || 1e-9)) * 100).toFixed(0)}%`;
|
||||
const s = head.size;
|
||||
let md = `## Performance on a big network\n\n${s.pops} POPs · ${s.links} links · ${s.pni} PNIs · ${s.caches} cache boxes · ${s.ix} IX ports · ${s.customers} customers. Median of ${RUNS} runs, in milliseconds, headless.\n\n`;
|
||||
md += base ? '| What | Base | This PR | Change | |\n|---|--:|--:|--:|---|\n' : '| What | Time |\n|---|--:|\n';
|
||||
for (const [k, label] of METRICS) {
|
||||
const r = res[k];
|
||||
md += base ? `| ${label} | ${ms(r.base)} | ${ms(r.head)} | ${pct(r)} | ${verdict(r)} |\n` : `| ${label} | ${ms(r.head)} |\n`;
|
||||
}
|
||||
if (base) {
|
||||
md += `\n${sameOutcome ? '✅ Routing results are identical to the base.' : '⚠️ Routing results differ from the base: traffic is carried differently. Expected if this PR changes gameplay; a bug if it only promises to be faster.'}\n`;
|
||||
const slow = METRICS.filter(([k]) => /slower/.test(verdict(res[k])));
|
||||
md += slow.length ? `\n**Slower:** ${slow.map(([, l]) => l).join(', ')}. Please explain or fix before merging.\n` : '\nNo slowdowns beyond noise.\n';
|
||||
}
|
||||
if (errs.length) md += `\n⚠️ Page errors while benchmarking:\n\n${errs.slice(0, 5).map((e) => '- `' + String(e).slice(0, 200).replace(/`/g, "'") + '`').join('\n')}\n`;
|
||||
md += `\n<sub>scripts/perf-bench.js · jsdom with a recording canvas: our JavaScript, not the browser's painting. Below about 2 ms, differences are noise.</sub>\n`;
|
||||
|
||||
console.log(md);
|
||||
const out = opt('--md', null); if (out) fs.writeFileSync(out, md);
|
||||
const sum = opt('--summary', null); if (sum) fs.appendFileSync(sum, md + '\n');
|
||||
const js = opt('--json', null); if (js) fs.writeFileSync(js, JSON.stringify({ size: s, runs: RUNS, results: res, sameOutcome, errors: errs }, null, 2));
|
||||
39
scripts/perf-fixture.js
Normal file
39
scripts/perf-fixture.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
#!/usr/bin/env node
|
||||
// Builds tests/fixtures/big-network.json: a deterministic, very large late-game network that the performance
|
||||
// benchmark (scripts/perf-bench.js) loads into the base and the head of every pull request. Big on purpose: about
|
||||
// a hundred POPs, a few hundred links and customers, and close to a thousand PNIs and cache boxes, like the saves
|
||||
// that made the game lag (#89). Regenerate only when the save format changes in a way old saves cannot load:
|
||||
// node scripts/perf-fixture.js
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('../tests/harness');
|
||||
|
||||
const { ev, errors } = load({ seed: 4242 });
|
||||
ev(`(()=>{UI.pitched=true;ACT.start({});S.cash=1e13;S.lvl=LEVELS.length;S.won=true;for(const g of GOALS)S.done[g.id]=0;S.tut=null;
|
||||
const top=RG.findIndex(r=>r.lvl===LEVELS.length&&r.maxP===PORT.length-1);
|
||||
const cs=ALLC.filter(c=>!CITY[c].ixOnly&&!CITY[c].cn);
|
||||
for(const c of cs){if(!S.pops[c])ACT.buildPop({city:c});const p=S.pops[c];if(!p)continue;p.rgen=top>=0?top:RG.length-1;p.routers=RMAX;if(!p.bb)ACT.launchBB({city:c});if(p.bb)p.bb.d=CITY[c].P*0.65;if(Math.random()<0.3)ACT.addSite({city:c});}
|
||||
const pops=Object.keys(S.pops);
|
||||
// A backbone: every POP to its two nearest neighbours, plus long-haul shortcuts.
|
||||
const L=(a,b,t)=>{if(a===b)return;UI.pending=null;UI.via=null;UI.lmode='wave';UI.route='diverse';try{openLinkModal(a,b);ACT.buildLink({tier:t});closeModal();}catch(e){closeModal();}};
|
||||
for(const a of pops){const near=pops.filter(b=>b!==a).sort((x,y)=>kmBetween(a,x)-kmBetween(a,y)).slice(0,2);for(const b of near)if(!pairLinks(a,b).length)L(a,b,3);}
|
||||
for(let i=0;i<60;i++){const a=pops[Math.floor(Math.random()*pops.length)],b=pops[Math.floor(Math.random()*pops.length)];L(a,b,4);}
|
||||
// Transit in some cities, IX ports with route servers everywhere.
|
||||
for(const c of pops.slice(0,30)){const ts=NETS.filter(n=>n.price&&n.pops.includes(c)&&(n.type==='t1'||n.type==='t2')).slice(0,2);for(const t of ts)ACT.buyTransit({city:c,net:t.id,tier:3});}
|
||||
for(const c of pops)for(const x of ixIdsIn(c)){try{ACT.buyIx({city:x,tier:3});}catch(e){}if(S.dk&&S.dk.q){S.dk.q=null;}closeModal();if(S.ixp[x]!==undefined&&!S.rs[x])ACT.rs({city:x});}
|
||||
compute();
|
||||
// PNIs wherever a network is present, and cache boxes from every CDN.
|
||||
for(const n of NETS)for(const c of pops)if(S.pni.length<950&&n.pops.includes(c)&&!n.tail)S.pni.push({id:'p'+n.id+'_'+c,net:n.id,city:c,tier:3,n:1,site:'a'});
|
||||
for(const n of NETS.filter(n=>n.cache))for(const c of pops)for(const k of [1,2])if(S.caches.length<850)S.caches.push({id:'c'+k+n.id+'_'+c,city:c,net:n.id,site:'a'});
|
||||
// Real customers: accept offers until there are a few hundred.
|
||||
for(let i=0;i<6000&&S.biz.length<420;i++){S.offers=[];spawnOffer();const o=S.offers[0];if(o&&bHas(o))ACT.accept({id:o.id});}
|
||||
S.offers=[];S.nextFail=S.day+30;S.nextEvent=S.day+30;S.inc=[];
|
||||
for(let d=0;d<20;d++)dayTick();
|
||||
})()`);
|
||||
if (errors.length) { console.error(errors); process.exit(1); }
|
||||
const save = ev('JSON.stringify(S)');
|
||||
const n = JSON.parse(ev("JSON.stringify({pops:Object.keys(S.pops).length,links:S.links.length,pni:S.pni.length,caches:S.caches.length,biz:S.biz.length,transit:S.transit.length,ix:Object.keys(S.ixp).length,served:Math.round(R.served)})"));
|
||||
const out = path.join(__dirname, '..', 'tests', 'fixtures', 'big-network.json');
|
||||
fs.mkdirSync(path.dirname(out), { recursive: true });
|
||||
fs.writeFileSync(out, save + '\n');
|
||||
console.log(`wrote ${path.relative(process.cwd(), out)} (${Math.round(save.length / 1024)} KB):`, n);
|
||||
Loading…
Add table
Add a link
Reference in a new issue