Files
Train/apps/api/bench.mjs
T
2026-06-16 00:55:20 +08:00

40 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 简易性能基准 — 对应 T-1.8 性能验收。
// 用法:先启动 APInode dist/main.js),再 `node bench.mjs`
const BASE = process.env.BENCH_BASE || 'http://127.0.0.1:3001';
const N = Number(process.env.BENCH_N || 200);
function pct(arr, p) {
const s = [...arr].sort((a, b) => a - b);
return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))];
}
async function bench(name, path, threshold) {
const lat = [];
// 预热
for (let i = 0; i < 5; i++) await fetch(`${BASE}${path}`);
for (let i = 0; i < N; i++) {
const t = performance.now();
const res = await fetch(`${BASE}${path}`);
await res.text();
lat.push(performance.now() - t);
}
const p50 = pct(lat, 50);
const p95 = pct(lat, 95);
const ok = p95 < threshold;
console.log(
`${ok ? '✓' : '✗'} ${name.padEnd(16)} p50=${p50.toFixed(1)}ms ` +
`p95=${p95.toFixed(1)}ms (阈值 ${threshold}ms)`,
);
return ok;
}
const results = [];
results.push(await bench('list', '/api/models?pageSize=24', 1500));
results.push(await bench('list+filter', '/api/models?category=动车组&sort=max_speed_value&order=desc', 1500));
results.push(await bench('detail', '/api/models/1', 1500));
results.push(await bench('search', '/api/search?q=HXD', 500));
const allOk = results.every(Boolean);
console.log(`\n基准结果:${allOk ? '全部达标 ✓' : '存在未达标项 ✗'}(每项 ${N} 次请求)`);
process.exit(allOk ? 0 : 1);