wrk 基准测试
安装与基础用法
# 安装
# macOS: brew install wrk
# Ubuntu: sudo apt install wrk
wrk -t2 -c10 -d30s http://localhost:3000/
# -t 线程数(通常为 CPU 核数的 2 倍)
# -c 总连接数
# -d 持续时间(支持 s/m/h 后缀)
# -H 额外请求头
wrk -t4 -c100 -d30s http://localhost:3000/api/users
wrk -t8 -c200 -d1m -H "Authorization: Bearer token" https://api.example.com/
Lua 脚本 — 自定义请求
-- post.lua — POST JSON 请求
wrk.method = "POST"
wrk.headers["Content-Type"] = "application/json"
wrk.body = '{"username":"testuser","password":"testpass"}'
-- 运行:wrk -t4 -c50 -d30s -s post.lua http://localhost:3000/api/login
---
-- multiple_paths.lua — 随机请求不同接口
paths = {"/api/users", "/api/products", "/api/orders"}
request = function()
path = paths[math.random(#paths)]
return wrk.format("GET", path)
end
高级 Lua 脚本
response = function(status, headers, body)
if status ~= 200 then
io.write("错误: " .. status .. "\n")
end
end
done = function(summary, latency, requests)
for _, p in pairs({50, 75, 90, 99}) do
n = latency:percentile(p)
io.write(string.format(" P%g: %0.2f ms\n", p, n / 1000))
end
end
结果解读
Running 30s test @ http://localhost:3000/
4 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 12.34ms 4.56ms 234.78ms 89.23%
延迟分布
50% 11.23ms ← P50 中位数
90% 17.89ms ← P90
99% 34.56ms ← P99
96,294 requests in 30.10s, 21.20MB read
Requests/sec: 3198.47 ← 吞吐量(RPS)
# 关键指标:
# Latency Avg — 平均响应时间
# Latency 99% — 99 百分位(最慢 1% 的请求)
# Req/sec — 吞吐量
# Socket errors — 连接错误(大于 0 是危险信号)
wrk2 — 恒定吞吐量模式
# wrk2 支持速率限制,模拟更真实的负载
# brew install wrk2
# 精确控制 1000 RPS
wrk2 -t4 -c100 -d30s -R 1000 http://localhost:3000/
# 使用场景对比:
# wrk — 寻找最大吞吐量(max RPS)
# wrk2 — 在目标 RPS 下测量延迟
参数速查表
| 参数 | 说明 | 示例 |
|---|---|---|
-t | 线程数 | -t4 |
-c | 总连接数 | -c100 |
-d | 持续时间 | -d30s、-d2m |
-s | Lua 脚本文件 | -s post.lua |
-H | HTTP 请求头 | -H "Auth: Bearer x" |
--latency | 打印延迟统计 | --latency |
-R (wrk2) | 目标 RPS | -R1000 |