From 6ed34ac6999693c0b3866cbb9cca1829bf6c6377 Mon Sep 17 00:00:00 2001 From: Kiko Beats Date: Wed, 28 Oct 2026 19:42:12 +0100 Subject: [PATCH] ci: add benchmark workflow Cases: - decode windows-1250 from content-type - decode shift_jis from meta charset - infer shift_jis with jschardet Co-Authored-By: Claude Opus 5.5 --- .github/workflows/benchmark.yml | 132 +++++++++++++++++++++++++++++++ .gitignore | 3 + benchmark/index.js | 135 ++++++++++++++++++++++++++++++++ package.json | 1 + 4 files changed, 271 insertions(+) create mode 100644 .github/workflows/benchmark.yml create mode 100644 benchmark/index.js diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml new file mode 100644 index 0000000..7c0b449 --- /dev/null +++ b/.github/workflows/benchmark.yml @@ -0,0 +1,132 @@ +name: benchmark + +on: + pull_request: + +permissions: + contents: read + pull-requests: write + +env: + pnpm_config_dangerously_allow_all_builds: true + SKIP_INSTALL_SIMPLE_GIT_HOOKS: true + +jobs: + benchmark: + name: Benchmark + runs-on: ubuntu-latest + steps: + - name: Checkout head + uses: actions/checkout@v7 + with: + path: head + persist-credentials: false + - name: Checkout base + uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.base.sha }} + path: base + persist-credentials: false + - name: Setup Node.js + uses: actions/setup-node@v7 + with: + node-version: lts/* + - name: Setup PNPM + uses: pnpm/action-setup@v6 + with: + version: latest + - name: Install head + working-directory: head + run: pnpm install + - name: Install base + working-directory: base + run: | + [ -f benchmark/index.js ] || exit 0 + pnpm install || { + echo "::warning::base install failed, comparing without it" + rm benchmark/index.js + } + - name: Run base and head alternately + env: + ROUNDS: 5 + run: | + set -euo pipefail + mkdir -p results + run_side () { + if [ "$1" = base ] && [ ! -f base/benchmark/index.js ]; then return 0; fi + if (cd "$1" && node benchmark/index.js) && [ -f "$1/benchmark-output.json" ]; then + mv "$1/benchmark-output.json" "results/$1-$2.json" + elif [ "$1" = base ]; then + echo "::warning::base benchmark failed in round $2, comparing without it" + else + exit 1 + fi + } + for round in $(seq "$ROUNDS"); do + if [ $((round % 2)) -eq 1 ]; then run_side base "$round"; run_side head "$round" + else run_side head "$round"; run_side base "$round"; fi + done + - name: Compare + env: + NAME: html-encode + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + node - <<'EOF' + const { readdirSync, readFileSync, writeFileSync, mkdirSync, appendFileSync } = require('fs') + const median = values => { + const sorted = [...values].sort((a, b) => a - b) + const middle = sorted.length >> 1 + return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2 + } + const round = value => Number(value.toFixed(2)) + const readSide = side => + readdirSync('results') + .filter(file => file.startsWith(`${side}-`)) + .map(file => JSON.parse(readFileSync(`results/${file}`, 'utf8'))) + const merge = runs => { + const names = [...new Set(runs.flatMap(run => run.map(result => result.name)))] + return names.map(name => { + const matches = runs.flatMap(run => run.filter(result => result.name === name)) + const values = matches.map(result => result.value) + return { + name, + unit: matches[0].unit, + value: round(median(values)), + range: `${round(Math.min(...values))}-${round(Math.max(...values))}`, + extra: `median of ${values.length} rounds: ${values.join(', ')}` + } + }) + } + const head = merge(readSide('head')) + const baseRuns = readSide('base') + const base = baseRuns.length ? merge(baseRuns) : [] + writeFileSync('head-output.json', JSON.stringify(head, null, 2)) + mkdirSync('cache', { recursive: true }) + const seed = base.length + ? { [process.env.NAME]: [{ commit: { id: process.env.BASE_SHA }, date: Date.now(), tool: 'customSmallerIsBetter', benches: base }] } + : {} + writeFileSync('cache/benchmark-data.json', JSON.stringify({ lastUpdate: Date.now(), repoUrl: '', entries: seed })) + const rows = head.map(current => { + const previous = base.find(result => result.name === current.name) + const ratio = previous ? (current.value / previous.value).toFixed(2) : '' + const format = result => (result ? `${result.value} ${result.unit}` : '') + return `| \`${current.name}\` | ${format(previous)} | ${format(current)} | ${ratio} |` + }) + const summary = ['| case | base | head | head/base |', '|-|-|-|-|', ...rows].join('\n') + console.log(summary) + appendFileSync(process.env.GITHUB_STEP_SUMMARY, summary + '\n') + EOF + - name: Comment + if: github.event.pull_request.head.repo.full_name == github.repository + uses: benchmark-action/github-action-benchmark@v1.22.2 + with: + name: html-encode + tool: customSmallerIsBetter + output-file-path: head-output.json + external-data-json-path: cache/benchmark-data.json + github-token: ${{ secrets.GITHUB_TOKEN }} + auto-push: false + comment-always: true + comment-on-alert: false + fail-on-alert: false + summary-always: false diff --git a/.gitignore b/.gitignore index 415e2bc..1aa3fbd 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,6 @@ npm-debug.log .nyc_output .DS_Store .envrc +benchmark-output.json +head-output.json +cache/ diff --git a/benchmark/index.js b/benchmark/index.js new file mode 100644 index 0000000..4207840 --- /dev/null +++ b/benchmark/index.js @@ -0,0 +1,135 @@ +'use strict' + +const { readFileSync, writeFileSync } = require('fs') +const { join } = require('path') +const { setFlagsFromString } = require('v8') +const { runInNewContext } = require('vm') +const iconv = require('iconv-lite') + +const toUTF8 = require('..')('utf-8') + +const RUNS = 7 +const HEADER_DECODES = 1200 +const META_DECODES = 10000 +const INFERRED_DECODES = 300 + +const DECLARED_CHARSET = /(?:charset|encoding)\s*=\s*['"]?shift_jis['"]?/gi + +const fixture = name => readFileSync(join(__dirname, '..', 'test', 'fixtures', name)) + +const polish = fixture('rp.pl.html') +const shiftJis = fixture('51242_54045.html') +const undeclaredShiftJis = iconv.encode( + iconv.decode(shiftJis, 'shift_jis').replace(DECLARED_CHARSET, ''), + 'shift_jis' +) + +const decodeCase = ({ name, buffer, contentType, decodes, expected }) => ({ + name, + extra: `${decodes} decodes of ${buffer.length} bytes`, + timed: () => { + let matched = 0 + for (let decode = 0; decode < decodes; decode++) { + if (toUTF8(buffer, contentType).includes(expected)) matched++ + } + return matched + }, + verify: matched => matched === decodes +}) + +const CASES = [ + decodeCase({ + name: 'decode windows-1250 from content-type', + buffer: polish, + contentType: 'text/html; charset=windows-1250', + decodes: HEADER_DECODES, + expected: 'majątków' + }), + decodeCase({ + name: 'decode shift_jis from meta charset', + buffer: shiftJis, + contentType: 'text/html', + decodes: META_DECODES, + expected: '或る日の小せん' + }), + decodeCase({ + name: 'infer shift_jis with jschardet', + buffer: undeclaredShiftJis, + contentType: 'text/html', + decodes: INFERRED_DECODES, + expected: '或る日の小せん' + }) +] + +const median = values => { + const sorted = values.slice().sort((a, b) => a - b) + return sorted[Math.floor(sorted.length / 2)] +} + +setFlagsFromString('--expose-gc') +const collectGarbage = runInNewContext('gc') + +const now = () => process.hrtime.bigint() + +const elapsed = started => Number(now() - started) / 1e6 + +const fmt = value => value.toFixed(1) + +const report = slot => { + const med = slot.walls.length ? median(slot.walls) : Number.NaN + const min = slot.walls.length ? Math.min(...slot.walls) : Number.NaN + const max = slot.walls.length ? Math.max(...slot.walls) : Number.NaN + const extra = `${slot.entry.extra}, errors ${slot.errors}, runs ${RUNS}` + console.log(`${slot.entry.name} median ${fmt(med)}ms range ${fmt(min)}-${fmt(max)} ${extra}`) + return { + name: slot.entry.name, + unit: 'ms', + value: Number(med.toFixed(1)), + range: `${fmt(min)}-${fmt(max)}`, + extra + } +} + +const takeSample = (slot, run) => { + try { + collectGarbage() + const started = now() + const outcome = slot.entry.timed() + const wall = elapsed(started) + if (!slot.entry.verify(outcome)) { + console.error(`${slot.entry.name} run ${run} produced unexpected output`) + slot.errors++ + return + } + slot.walls.push(wall) + } catch (error) { + console.error(error) + slot.errors++ + } +} + +const main = () => { + const slots = CASES.map(entry => ({ entry, walls: [], errors: 0 })) + for (const slot of slots) { + try { + slot.entry.timed() + } catch (error) { + console.error(error) + slot.errors++ + } + } + for (let run = 0; run < RUNS; run++) { + for (const slot of slots) takeSample(slot, run) + } + const results = slots.map(report) + writeFileSync( + join(__dirname, '..', 'benchmark-output.json'), + JSON.stringify(results, null, 2) + '\n' + ) + const errors = slots.reduce((total, slot) => total + slot.errors, 0) + if (errors > 0 || results.some(result => !Number.isFinite(result.value))) { + process.exitCode = 1 + } +} + +main() diff --git a/package.json b/package.json index aa19cd1..002a20e 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "index.js" ], "scripts": { + "benchmark": "node benchmark/index.js", "clean": "rm -rf node_modules", "contributors": "(npx git-authors-cli && npx finepack && git add package.json && git commit -m 'build: contributors' --no-verify) || true", "coveralls": "nyc report --reporter=text-lcov | coveralls",