1. 準備測試環境
在進行性能測試前,需確保Linux環境與生產環境一致(包括硬件配置、Node.js版本、依賴庫版本)??赏ㄟ^node -v
確認Node.js版本,使用uname -a
檢查Linux內核版本。安裝必要工具(如wrk
、autocannon
):
# 安裝wrk(以Ubuntu為例)
sudo apt update && sudo apt install -y build-essential libssl-dev git
git clone https://github.com/wg/wrk.git && cd wrk
make && sudo cp wrk /usr/local/bin/
# 安裝autocannon
npm install -g autocannon
這些步驟可避免環境差異導致的測試結果偏差。
2. 選擇性能測試工具
根據測試目標選擇工具:
wrk
(現代、高并發,支持Lua腳本擴展)、autocannon
(易用,支持HTTP/2)、ApacheBench(ab)
(簡單,適合快速測試);perf_hooks
(Node.js內置,測量代碼塊執行時間)、V8 Profiler
(分析CPU熱點函數);top
(實時查看CPU/內存占用)、vmstat
(監控系統整體性能)、iostat
(分析磁盤I/O)。3. 執行負載測試
以wrk
和autocannon
為例,模擬高并發請求:
wrk -t12 -c400 -d30s --latency http://localhost:3000/api endpoint
參數說明:-t12
(12個線程)、-c400
(400個并發連接)、-d30s
(持續30秒)、--latency
(顯示延遲分布)。autocannon -c 100 -d 50 -p 10 http://localhost:3000/api endpoint
參數說明:-c 100
(100個并發)、-d 50
(50秒持續時間)、-p 10
(每10秒打印一次進度)。4. 進行代碼級性能分析
const { performance } = require('perf_hooks');
const start = performance.now();
// 模擬耗時操作(如數據庫查詢、復雜計算)
for (let i = 0; i < 1000000; i++) {}
const end = performance.now();
console.log(`耗時:${end - start} 毫秒`);
const profiler = require('v8-profiler-next');
const snapshot = profiler.takeSnapshot('CPU Profile');
snapshot.export((err, result) => {
if (err) throw err;
require('fs').writeFileSync('cpu-profile.json', result);
console.log('CPU快照已保存為cpu-profile.json');
});
使用speedscope
工具打開cpu-profile.json
,查看占用CPU時間最多的函數,定位性能瓶頸。5. 監控系統資源
測試時,通過以下命令實時監控系統資源使用情況:
M
鍵按內存排序,按P
鍵按CPU排序;6. 分析結果與優化
async/await
或Promise
避免阻塞事件循環;stream
模塊,減少內存占用。