目 录CONTENT

文章目录

API性能自测:WRK(Http 协议的基准测试工具)

Administrator
2025-11-09 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

 

字数 1625,阅读大约需 9 分钟

API性能测试:WRK(Http 协议的基准测试工具)

刚刷到的朋友注意啦!点击【关注】锁定宝藏库,从此升职加薪不迷路 ✨


本篇核心

优点

在fastapi或者是python web开发过程中,掌握API基本的性能,是必要的指标。本文主要推荐快速进行API压测的工具WRK,轻量级性能测试工具,强调单机开发自测,应付后端开发人员的接口性能验证。基于系统自带的高性能 I/O 机制,如 epoll, kqueue, 利用异步的事件驱动框架,通过很少的线程就可以压出很大的并发量。

  1. 1. 单机高负载:C语言编写,基于epoll/kqueue,单机可产生数十万QPS

  2. 2. 资源占用低:相比JMeter等工具,CPU和内存占用极小

  3. 3. 多线程架构:充分利用多核CPU性能

缺点

不支持:WebSocket、gRPC、数据库、消息队列等


安装WRK

我的开发环境是Ubuntu,因此安装的是Ubuntu版本,其他操作系统可根据参考文章自行选择安装。
Ubuntu:root@DESKTOP-QJ0UM8D:~# apt-get install -y wrk
其他参考:HTTP压测工具wrk安装与使用-腾讯云开发者社区-腾讯云[1]

工具参数说明

wrk 性能测试工具详解

wrk 是一个现代化的 HTTP 基准测试工具,能够在单机上产生大量负载来测试 API/Web 服务的性能。

基本用法

参数由小到大,一次增加,找到瓶颈。


    
    
    
  wrk -t12 -c400 -d30s http://localhost:9100/api/v1/endpoint

核心参数说明

参数

说明

示例

-t, --threads

使用的线程数

-t12 (12个线程)

-c, --connections

保持打开的HTTP连接数

-c400 (400个并发连接)

-d, --duration

测试持续时间

-d30s (30秒), -d5m (5分钟)

-H, --header

添加请求头

-H "Authorization: Bearer token"

--latency

打印延迟统计信息

显示百分位延迟

--timeout

超时时间

--timeout 2s

-s, --script

加载 Lua 脚本

-s post.lua (复杂场景)

多种模式说明

1. 基础 GET 请求测试


    
    
    
  wrk -t4 -c100 -d30s --latency http://api.example.com/users
  • • 4个线程

  • • 100个并发连接

  • • 持续30秒

  • • 显示延迟统计

2. 带请求头的测试


    
    
    
  wrk -t8 -c200 -d1m \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  --latency \
  http://api.example.com/data

3. POST 请求测试(使用 Lua 脚本)

创建 post.lua 文件:


    
    
    
  wrk.method = "POST"
wrk.body   = '{"username":"test","password":"123456"}'
wrk.headers["Content-Type"] = "application/json"

执行测试:


    
    
    
  wrk -t4 -c100 -d30s -s post.lua http://api.example.com/login

4. 复杂场景:动态请求体

创建 dynamic.lua


    
    
    
  -- 每个请求生成不同的数据
request = function()
  local id = math.random(1, 10000)
  local body = string.format('{"user_id":%d,"action":"query"}', id)
  
  return wrk.format("POST", "/api/user", 
    {["Content-Type"] = "application/json"}, 
    body)
end

    
    
    
  wrk -t8 -c200 -d60s -s dynamic.lua http://api.example.com

输出指标说明

最核心:时间延迟和QPS

关键指标

指标

含义

Latency (延迟)

请求响应时间

- Avg

平均延迟

- Stdev

标准差(波动程度)

- Max

最大延迟

Req/Sec

每秒请求数(每线程)

Latency Distribution

延迟分布百分位

Requests/sec

总体 QPS(每秒查询数)

Transfer/sec

每秒传输数据量

高级 Lua 脚本技巧

待补充

参数调优建议


    
    
    
  # 轻量测试(开发环境)
wrk -t2 -c10 -d10s --latency http://localhost:8080/api

# 中等压力(预发布环境)
wrk -t8 -c200 -d60s --latency http://staging.api.com

# 高压测试(压测环境)
wrk -t12 -c1000 -d300s --latency --timeout 10s http://test.api.com

线程数建议

  • • 通常设置为 CPU 核心数的 1-2 倍

  • 过多线程会导致上下文切换开销


自测演示:sync同步DB

结合前面文章fastapi开发的用户管理API,我们对查询用户列表接口,进行性能自测。

常规命令压测

测试时长: 30秒
并发连接: 100个
线程数: 4个
目标API: /api/v1/fastapi-demo/user/ (分页查询)

✅ QPS约380:每秒可以处理380个请求


    
    
    
  root@DESKTOP-QJ0UM8D:~# wrk -t4 -c100 -d30s \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjMxMzYyMTYsInN1YiI6IjEifQ.sr3JYgRdkOjmDRyeclSGDpzX4qz59r-h3aHBa7m5zfo" \
  -H "Accept: */*" \
  -H "Connection: keep-alive" \
  --latency \
  "http://localhost:9100/api/v1/fastapi-demo/user/?skip=0&limit=100"
Running 30s test @ http://localhost:9100/api/v1/fastapi-demo/user/?skip=0&limit=100
  4 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   262.45ms   42.58ms 810.34ms   82.81%
    Req/Sec    95.44     29.02   220.00     71.42%
  Latency Distribution
     50%  254.30ms
     75%  275.36ms
     90%  313.98ms
     99%  359.72ms
  11367 requests in 29.93s, 4.41MB read
Requests/sec:    379.82
Transfer/sec:    150.99KB

lua脚本压测


    
    
    
  wrk -t4 -c100 -d30s \
  -s test_user_api.lua \
  "http://localhost:9100/api/v1/fastapi-demo/user/?skip=0&limit=100"

    
    
    
  -- 设置请求头
wrk.headers["Authorization"] = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjMxMzYyMTYsInN1YiI6IjEifQ.sr3JYgRdkOjmDRyeclSGDpzX4qz59r-h3aHBa7m5zfo"
wrk.headers["Accept"] = "*/*"
wrk.headers["Connection"] = "keep-alive"

-- 统计变量
local success = 0
local errors = 0
local status_codes = {}

-- 响应处理
response = function(status, headers, body)
  -- 统计状态码
  status_codes[status] = (status_codes[status] or 0) + 1
  
  if status == 200 then
    success = success + 1
  else
    errors = errors + 1
    print("Error Status: " .. status)
  end
end

-- 测试完成后的汇总
done = function(summary, latency, requests)
  print("\n=== 测试汇总 ===")
  print("总请求数: " .. summary.requests)
  print("成功请求: " .. success)
  print("失败请求: " .. errors)
  print("成功率: " .. string.format("%.2f%%", (success / summary.requests * 100)))
  
  print("\n状态码分布:")
  for code, count in pairs(status_codes) do
    print("  " .. code .. ": " .. count)
  end
  
  print("\n延迟统计:")
  print("  平均延迟: " .. string.format("%.2fms", latency.mean / 1000))
  print("  最小延迟: " .. string.format("%.2fms", latency.min / 1000))
  print("  最大延迟: " .. string.format("%.2fms", latency.max / 1000))
  print("  50%请求: " .. string.format("%.2fms", latency:percentile(50) / 1000))
  print("  90%请求: " .. string.format("%.2fms", latency:percentile(90) / 1000))
  print("  99%请求: " .. string.format("%.2fms", latency:percentile(99) / 1000))
end

自测演示:async异步DB

测试时长: 30秒
并发连接: 100个
线程数: 4个
目标API: /api/v1/fastapi-demo/user/aynsc/ (异步分页查询)


    
    
    
  root@DESKTOP-QJ0UM8D:~# wrk -t4 -c100 -d30s   -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NjMxMzYyMTYsInN1YiI6IjEifQ.sr3JYgRdkOjmDRyeclSGDpzX4qz59r-h3aHBa7m5zfo"   -H "Accept: */*"   -H "Connection: keep-alive"   --latency   "http://localhost:9100/api/v1/fastapi-demo/user/async/?skip=0&limit=100"
Running 30s test @ http://localhost:9100/api/v1/fastapi-demo/user/async/?skip=0&limit=100
  4 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   310.79ms   72.78ms   1.91s    92.44%
    Req/Sec    80.26     30.25   170.00     65.06%
  Latency Distribution
     50%  288.60ms
     75%  342.14ms
     90%  372.21ms
     99%  447.97ms
  9605 requests in 29.43s, 3.73MB read
  Socket errors: connect 0, read 0, write 0, timeout 102
Requests/sec:    326.37


结尾彩蛋

刚刷到的朋友注意啦!点击【关注】锁定宝藏库,从此升职加薪不迷路 ✨
若觉得内容有用,长按点赞!你的每次互动,都是我深夜码字的星光 🌟

【三步操作,终身受益】
✅ 点击「关注」→ 持续收获成长能量
✅ 点亮「点赞」→ 为干货内容打call
✅ 设为「星标」⭐️→ 算法优先推送,更新不错过



广告时刻

📢 云资源限时福利
有云服务器、CDN、对象存储、网络防护等需求的朋友,欢迎联系下方腾讯云官方销售 👇
✔️ 内部专属折扣,价格更优
✔️ 量大可谈,支持定制方案
✔️ 技术咨询与售后无忧

引用链接

[1] HTTP压测工具wrk安装与使用-腾讯云开发者社区-腾讯云: https://cloud.tencent.com/developer/article/2381728

 

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区