Ubuntu 下 Node.js 性能测试实操指南
一 测试准备与基线
二 负载与接口测试工具与命令
npx autocannon -c 100 -d 30 http://localhost:3000/api/ping
wrk -t12 -c400 -d30s http://localhost:3000/
ab -n 1000 -c 50 http://localhost:3000/
bombardier -c 100 -d 30s http://localhost:3000/
三 应用内性能测量与日志埋点
const express = require('express');
const morgan = require('morgan');
const app = express();
morgan.token('response-time-ms', (req, res) => {
return res.getHeader('X-Response-Time') || '-';
});
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
res.setHeader('X-Response-Time', `${duration}ms`);
console.log(`${req.method} ${req.url} ${res.statusCode} ${duration}ms`);
});
next();
});
四 深入诊断与内存分析
npx clinic doctor -- node app.js
npx clinic flame -- node app.js
const heapdump = require('heapdump');
heapdump.writeSnapshot((err, filename) => console.log(filename));
node --inspect app.js
# 打开 chrome://inspect 连接并采集快照
五 自动化与版本对比脚本
#!/usr/bin/env bash
set -e
VERSIONS=("16" "18" "20" "22")
RESULTS="perf-$(date +%F).csv"
echo "version,timestamp,startup_ms,rss_mb,throughput_rps,p95_ms" > "$RESULTS"
for V in "${VERSIONS[@]}"; do
echo "=== Testing Node.js $V ==="
nvm use "$V" >/dev/null
FULL=$(node -v)
TS=$(date +%s)
# 启动被测服务(示例:node server.js)
node server.js &
PID=$!
sleep 5
# 启动时间(简化测量)
STARTUP_MS=$( (time node -e "" 2>&1) | awk '/real/ {print $2*1000}' )
# RSS 内存(MB)
RSS_MB=$(node -e "console.log(Math.round(process.memoryUsage().rss/1024/1024))")
# HTTP 基准(并发 50,持续 10s)
OUT=$(npx autocannon -c 50 -d 10 http://localhost:3000/api/ping)
THROUGHPUT=$(echo "$OUT" | grep -E 'Requests/sec' | awk '{print $2}')
P95=$(echo "$OUT" | grep -E '95%' | awk '{print $2}')
kill "$PID" || true
echo "$FULL,$TS,$STARTUP_MS,$RSS_MB,$THROUGHPUT,$P95" >> "$RESULTS"
echo "Done: $FULL"
done
echo "Results saved to $RESULTS"