在 CentOS 上测试 Node.js 性能,可以从基准测试、压力测试、系统资源监控、火焰图分析几个层面来做。下面按常见场景给你一个实用清单。
node -v
npm -v
建议使用 LTS 版本(如 18.x / 20.x)
sudo yum install -y epel-release
sudo yum install -y htop sysstat
console.time(简单基准)console.time('test');
for (let i = 0; i < 1e6; i++) {}
console.timeEnd('test');
perf_hooksconst { performance } = require('perf_hooks');
const start = performance.now();
// 业务代码
const end = performance.now();
console.log(`耗时: ${end - start} ms`);
benchmark 模块npm install benchmark
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
suite
.add('循环', () => {
for (let i = 0; i < 1e6; i++) {}
})
.on('cycle', e => console.log(String(e.target)))
.run();
autocannonnpm install -g autocannon
autocannon -c 100 -d 10 http://localhost:3000/api
参数说明:
-c 并发数-d 持续时间(秒)sudo yum install -y httpd-tools
ab -n 10000 -c 100 http://localhost:3000/
sudo yum install -y wrk
wrk -t4 -c100 -d10s http://localhost:3000/
htop
top -p $(pgrep node)
iostat -x 1
node --cpu-prof app.js
会生成 .cpuprofile 文件,用 Chrome DevTools 打开分析。
node --heap-prof app.js
npm install -g clinic
clinic doctor -- node app.js
可自动生成:
| 指标 | 说明 |
|---|---|
| QPS / RPS | 每秒请求数 |
| Latency | P50 / P95 / P99 |
| CPU 使用率 | 是否单核跑满 |
| 内存增长 | 是否内存泄漏 |
| Event Loop Lag | 延迟是否过高 |
node app.js &
autocannon -c 200 -d 30 http://localhost:3000/
如果你愿意,可以告诉我:
我可以给你一套定制化测试方案。