benchmark.ts
This file
Path
benchmarks/http-server/benchmark.ts
326 lines · 10.0 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–326why, one step back1/**2 * Hono HTTP Performance Benchmark3 *4 * Inspired by https://github.com/SaltyAom/bun-http-framework-benchmark5 *6 * Usage:7 * bun run benchmark.ts [options]8 *9 * Options:10 * --baseline=<ref> Git reference for baseline (default: main)11 * --target=<ref> Git reference for target (default: current)12 * --runs=<number> Number of benchmark runs (default: 1)13 * --duration=<number> Duration of each test in seconds (default: 10)14 * --skip-tests Skip endpoint validation tests15 */1617import { spawn } from 'node:child_process'18import { existsSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'19import { join } from 'node:path'2021// Configuration from command line arguments22const baseline =23 process.argv.find((arg) => arg.startsWith('--baseline='))?.split('=')[1] || 'origin/main'24const target = process.argv.find((arg) => arg.startsWith('--target='))?.split('=')[1] || 'current'25const runs = parseInt(process.argv.find((arg) => arg.startsWith('--runs='))?.split('=')[1] || '1')26const duration = parseInt(27 process.argv.find((arg) => arg.startsWith('--duration='))?.split('=')[1] || '10'28)29const concurrency = 50030const skipTests = process.argv.includes('--skip-tests')3132const SCRIPT_DIR = import.meta.dirname33const TEMP_DIR = join(SCRIPT_DIR, '.benchmark-temp')34const HONO_ROOT = join(SCRIPT_DIR, '../..')3536// Test app template (embedded to avoid file dependency issues)37const getAppTemplate = () => `import { Hono } from './src/index.ts'38import { RegExpRouter } from './src/router/reg-exp-router/index.ts'3940const app = new Hono({ router: new RegExpRouter() })4142app43 .get('/', (c) => c.text('Hi'))44 .post('/json', (c) => c.req.json().then(c.json))45 .get('/id/:id', (c) => {46 const id = c.req.param('id')47 const name = c.req.query('name')48 c.header('x-powered-by', 'benchmark')49 return c.text(\`\${id} \${name}\`)50 })5152export default app`5354const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))5556const runCommand = async (command: string, cwd: string) => {57 const parts = command.split(' ')58 const proc = spawn(parts[0], parts.slice(1), { cwd })5960 let stdout = ''61 let stderr = ''6263 proc.stdout.on('data', (data) => {64 stdout += data65 })66 proc.stderr.on('data', (data) => {67 stderr += data68 })6970 const exitCode = await new Promise<number>((resolve) => {71 proc.on('close', resolve)72 })7374 if (exitCode !== 0) {75 console.error(`Command failed: ${command}`)76 console.error(`Exit code: ${exitCode}`)77 console.error(`Stdout: ${stdout}`)78 console.error(`Stderr: ${stderr}`)79 throw new Error(`Command failed: ${command}`)80 }8182 return { stdout, stderr }83}8485const setupTemp = () => {86 if (existsSync(TEMP_DIR)) {87 rmSync(TEMP_DIR, { recursive: true })88 }89 mkdirSync(TEMP_DIR, { recursive: true })90 writeFileSync(join(TEMP_DIR, 'body.json'), '{"hello":"world"}')91}9293const buildVersion = async (version: string, name: string) => {94 console.log(`📦 Preparing ${name} (${version})...`)9596 let needsRestore = false97 let stashRef = ''9899 if (version === 'current') {100 // No build needed - use src directly101 } else {102 // Ensure we have the latest remote refs103 await runCommand('git fetch origin', HONO_ROOT)104105 try {106 const stashResult = await runCommand('git stash push -m "benchmark-temp"', HONO_ROOT)107 needsRestore = stashResult.stdout.includes('Saved working directory')108 if (needsRestore) {109 stashRef = 'stash@{0}'110 }111 } catch {112 // No changes to stash113 }114115 await runCommand(`git checkout ${version}`, HONO_ROOT)116 await runCommand('bun install --frozen-lockfile', HONO_ROOT)117 // No build needed - use src directly118 }119120 const versionDir = join(TEMP_DIR, name)121 mkdirSync(versionDir, { recursive: true })122 await runCommand(`cp -r ${HONO_ROOT}/src ${versionDir}/src`, process.cwd())123124 const appPath = join(versionDir, 'app.ts')125 writeFileSync(appPath, getAppTemplate())126127 // Test endpoints (optional)128 if (!skipTests) {129 console.log(`🧪 Testing endpoints for ${name}...`)130 const server = spawn('bun', [appPath], {131 cwd: TEMP_DIR,132 env: { ...process.env, NODE_ENV: 'production' },133 })134 await sleep(2000)135136 try {137 const res1 = await fetch('http://127.0.0.1:3000/')138 if ((await res1.text()) !== 'Hi') {139 throw new Error('[GET /] test failed')140 }141142 const res2 = await fetch('http://127.0.0.1:3000/id/1?name=bun')143 if (res2.headers.get('x-powered-by') !== 'benchmark' || (await res2.text()) !== '1 bun') {144 throw new Error('[GET /id/:id] test failed')145 }146147 const body = JSON.stringify({ hello: 'world' })148 const res3 = await fetch('http://127.0.0.1:3000/json', {149 method: 'POST',150 body,151 headers: { 'content-type': 'application/json', 'content-length': body.length.toString() },152 })153 if (154 !res3.headers.get('content-type')?.includes('application/json') ||155 (await res3.text()) !== body156 ) {157 throw new Error('[POST /json] test failed')158 }159160 console.log(` ✅ Tests passed for ${name}`)161 } finally {162 server.kill()163 await sleep(1000)164 }165 } else {166 console.log(` ⏭️ Skipping endpoint tests for ${name}`)167 }168169 // Restore git state170 if (version !== 'current' && needsRestore) {171 await runCommand('git checkout -', HONO_ROOT)172 await runCommand(`git stash pop ${stashRef}`, HONO_ROOT)173 } else if (version !== 'current') {174 await runCommand('git checkout -', HONO_ROOT)175 }176177 return appPath178}179180const runBenchmark = async (appPath: string, name: string) => {181 console.log(`⚡ Running HTTP benchmark for ${name}...`)182183 const bodyFile = join(TEMP_DIR, 'body.json')184 const commands = [185 `bombardier --fasthttp -c ${concurrency} -d ${duration}s http://127.0.0.1:3000/`,186 `bombardier --fasthttp -c ${concurrency} -d ${duration}s http://127.0.0.1:3000/id/1?name=bun`,187 `bombardier --fasthttp -c ${concurrency} -d ${duration}s -m POST -H Content-Type:application/json -f ${bodyFile} http://127.0.0.1:3000/json`,188 ]189190 const allRuns: number[][] = []191192 for (let run = 0; run < runs; run++) {193 console.log(` Run ${run + 1}/${runs}`)194195 const server = spawn('bun', [appPath], {196 cwd: TEMP_DIR,197 env: { ...process.env, NODE_ENV: 'production' },198 })199 await sleep(1000)200201 const runResults: number[] = []202203 try {204 for (const command of commands) {205 const result = await runCommand(command, process.cwd())206 console.log(result.stdout)207208 const match = result.stdout.match(/Reqs\/sec\s+(\d+[.|,]\d+)/)209 if (match) {210 runResults.push(parseFloat(match[1].replace(',', '')))211 } else {212 console.log('❌ Failed to parse result')213 runResults.push(0)214 }215 }216 } finally {217 server.kill()218 await sleep(500)219 }220221 allRuns.push(runResults)222 }223224 const average = (arr: number[]) => arr.reduce((a, b) => a + b, 0) / arr.length225226 const ping = average(allRuns.map((run) => run[0]))227 const query = average(allRuns.map((run) => run[1]))228 const body = average(allRuns.map((run) => run[2]))229 const overall = (ping + query + body) / 3230231 return { name, average: overall, ping, query, body, runs: allRuns.map((run) => average(run)) }232}233234const main = async () => {235 console.log('🏁 Hono HTTP Benchmark')236 console.log('======================')237 console.log(`Baseline: ${baseline}`)238 console.log(`Target: ${target}`)239 console.log(`Runs: ${runs}`)240 console.log(`Duration: ${duration}s`)241 console.log(`Concurrency: ${concurrency}`)242 console.log(`Skip Tests: ${skipTests}`)243 console.log('')244245 setupTemp()246247 try {248 // Compare baseline vs target249 const baselinePath = await buildVersion(baseline, 'baseline')250 const targetPath = await buildVersion(target, 'target')251252 const baselineResult = await runBenchmark(baselinePath, 'baseline')253 const targetResult = await runBenchmark(targetPath, 'target')254255 // Calculate changes256 const calculateChange = (target: number, baseline: number) =>257 (((target - baseline) / baseline) * 100).toFixed(2)258259 const changes = {260 average: calculateChange(targetResult.average, baselineResult.average),261 ping: calculateChange(targetResult.ping, baselineResult.ping),262 query: calculateChange(targetResult.query, baselineResult.query),263 body: calculateChange(targetResult.body, baselineResult.body),264 }265266 // Format numbers267 const format = (num: number) => num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')268 const formatChange = (change: string) => (Number(change) >= 0 ? '+' : '') + change + '%'269270 // Generate table data271 const rows = [272 {273 framework: `hono (${baseline})`,274 runtime: 'bun',275 average: format(baselineResult.average),276 ping: format(baselineResult.ping),277 query: format(baselineResult.query),278 body: format(baselineResult.body),279 },280 {281 framework: `hono (${target})`,282 runtime: 'bun',283 average: format(targetResult.average),284 ping: format(targetResult.ping),285 query: format(targetResult.query),286 body: format(targetResult.body),287 },288 {289 framework: 'Change',290 runtime: '',291 average: formatChange(changes.average),292 ping: formatChange(changes.ping),293 query: formatChange(changes.query),294 body: formatChange(changes.body),295 },296 ]297298 const table = [299 '| Framework | Runtime | Average | Ping | Query | Body |',300 '| --- | --- | --- | --- | --- | --- |',301 ...rows.map(302 (row) =>303 `| ${row.framework} | ${row.runtime} | ${row.average} | ${row.ping} | ${row.query} | ${row.body} |`304 ),305 ]306307 // Console output308 console.log('')309 table.forEach((line) => console.log(line))310 console.log('')311312 // Markdown output313 const markdownOutput = ['## HTTP Performance Benchmark', '', ...table].join('\n')314315 writeFileSync(join(SCRIPT_DIR, 'benchmark-results.md'), markdownOutput)316 } catch (error) {317 console.error('❌ Benchmark failed:', error)318 throw error319 } finally {320 if (existsSync(TEMP_DIR)) {321 rmSync(TEMP_DIR, { recursive: true })322 }323 }324}325326main()