ab (ApacheBench) 是 Apache 附帶的 HTTP 壓力測試工具,輕量、易用、支援 KeepAlive、並發控制。本文詳細說明所有參數、關鍵輸出指標含義、結果分析方法、實戰壓測流程與常見誤區。
| 參數 | 完整名稱 | 說明 | 預設值 |
|---|---|---|---|
-n | requests | 總請求數 | 1 |
-c | concurrency | 並發數 (同時連線數) | 1 |
-t | timelimit | 最大測試秒數 (隱含 -n 50000) | 無限制 |
-p | postfile | POST 資料檔案路徑 | - |
-T | content-type | POST Content-Type 標頭 | text/plain |
-v | verbosity | 輸出詳細度 (1-4,4 顯示標頭) | 0 |
-w | html-table | 輸出 HTML 表格格式 | 否 |
-i | head | 使用 HEAD 而非 GET | 否 |
-k | keepalive | 啟用 HTTP KeepAlive | 否 |
-H | header | 自訂標頭 (可重複) | - |
-A | auth | Basic Auth 認證 user:pass | - |
-P | proxy-auth | Proxy Basic Auth | - |
-X | proxy | Proxy 伺服器 host:port | - |
-C | cookie | Cookie 標頭 name=value (可重複) | - |
-g | gnuplot | 輸出 gnuplot 格式資料檔 | - |
-e | csv | 輸出 CSV 百分位檔 | - |
-d | no-percentiles | 不顯示百分位表 | 否 |
-S | no-confidence | 不顯示信心估計與警告 | 否 |
# 基礎壓測:100 並發,10000 請求 ab -c 100 -n 10000 https://example.com/ # POST 壓測 (需檔案 post.txt 含 "param1=value1¶m2=value2") ab -c 50 -n 5000 -p post.txt -T "application/x-www-form-urlencoded" https://example.com/api # KeepAlive 測試 ab -c 100 -n 10000 -k https://example.com/ # 自訂標頭 (API Token) ab -c 100 -n 10000 -H "Authorization: Bearer token123" https://example.com/api # 輸出 CSV 供 Excel 分析 ab -c 100 -n 10000 -e result.csv https://example.com/ # 輸出 gnuplot 繪圖資料 ab -c 100 -n 10000 -g plot.data https://example.com/
Server Software: Apache/2.4.54 Server Hostname: example.com Server Port: 80 Document Path: / Document Length: 1234 bytes Concurrency Level: 100 Time taken for tests: 12.345 seconds Complete requests: 10000 Failed requests: 0 Non-2xx responses: 0 Total transferred: 14567890 bytes HTML transferred: 12340000 bytes Requests per second: 810.12 [#/sec] (mean) ← 核心吞吐指標 Time per request: 123.45 [ms] (mean) ← 平均延遲 (含並發) Time per request: 1.23 [ms] (mean, across all concurrent requests) ← 單請求處理時間 Transfer rate: 1152.34 [Kbytes/sec] received
| 指標 | 含義 | 關注重點 |
|---|---|---|
| Requests per second (RPS) | 每秒完成請求數 = 總請求 / 總耗時 | 系統吞吐能力核心指標,越高越好 |
| Time per request (mean) | 平均延遲 = 總耗時 / 總請求 × 並發數 | 使用者感知延遲,含排隊時間 |
| Time per request (across all) | 單請求處理時間 = 總耗時 / 總請求 | 伺服器純處理時間,不含並發排隊 |
| Transfer rate | 網路傳輸速率 | 排查頻寬瓶頸 |
| Failed requests | 失敗請求數 (非 2xx、連線錯誤、超時) | 必須為 0,否則系統不穩定 |
| Non-2xx responses | 非成功狀態碼回應數 | 業務邏輯錯誤 (4xx/5xx) |
Connection Times (ms)
min mean[+/-sd] median max
Connect: 2 5 1.2 4 25
Processing: 10 80 15.3 75 350
Waiting: 8 75 14.8 70 340
Total: 12 85 15.5 80 360
Percentage of the requests served within a certain time (ms) 50% 80 66% 90 75% 95 80% 100 90% 150 95% 200 98% 300 99% 340 100% 360 (longest request)
解讀:50% 請求 (中位數) 在 80ms 內完成,99% 在 340ms 內。關注 P99、P99.9 而非平均值,避免長尾延遲影響體驗。
-n 100000,遞增 -c 10, 50, 100, 200, 500, 1000,記錄 RPS、P99、錯誤率。-t 1800),觀察記憶體洩漏、RPS 抖動、錯誤率上升。tcpcopy 或 go-replay 將線上流量複製到測試環境。-k,否則 TCP 握手開銷佔比過大。https://example.com vs https://example.com/ 可能觸發 301 重導向,干擾結果。統一加斜線。wrk -t4 -c100 -d30s https://example.com/ (多執行緒、事件循環、Lua 腳本)。