在 Debian 上进行 Node.js 性能测试可按以下步骤操作,涵盖工具安装、测试方法及分析:
安装 Node.js 和 npm
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
sudo apt-get install -y nodejs
使用内置工具 perf_hooks
测量执行时间
// 示例代码:测量代码执行时间
const { performance } = require('perf_hooks');
const start = performance.now();
// 待测试代码(如循环、计算)
const end = performance.now();
console.log(`耗时:${end - start} 毫秒`);
运行:node your_script.js
使用 ApacheBench (ab) 进行 HTTP 压力测试
sudo apt install apache2-utils
ab -n 1000 -c 10 http://localhost:3000/ # 1000次请求,10并发
使用 wrk 进行高并发负载测试
sudo apt install wrk
wrk -t12 -c400 -d30s http://localhost:3000 # 12线程,400并发,持续30秒
使用 Benchmark.js 进行基准测试
npm install benchmark
创建 benchmark.js
:
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
suite.add('String.replace', () => 'hello'.replace(/./g, 'x'));
suite.run({ async: true });
运行:node benchmark.js
使用 Chrome DevTools 进行内存/性能分析
node --inspect-brk server.js # 启动应用并附加调试器
打开 Chrome 浏览器,访问 chrome://inspect
,使用 Performance 和 Memory 工具分析 CPU、内存占用。
使用第三方工具(如 Artillery)测试 API 性能
npm install -g artillery
artillery run scenarios.yml # 需提前编写测试场景文件
工具选择建议:
perf_hooks
或 Benchmark.js
;wrk
或 ApacheBench
;Artillery
或 JMeter
;Chrome DevTools
或 heapdump
。