跳转到内容

性能基准 (benchmark)

benchmark 是 GStack 中用于性能测试和对比的技能。它帮助你:量化性能,找到瓶颈,证明优化效果。

作为一个程序员,你可能经常遇到:

  • “我觉得性能还行”——但没有数据支持
  • “优化了但不知道效果”——没有对比数据
  • “不知道哪个方案更快”——没有 benchmark

benchmark 就是解决这些问题的。

❌ "这个 API 挺快的"
✅ "这个 API P50 响应时间 45ms,P99 120ms"

没有数据 = 无法优化

优化前:
- 首页加载 3 秒
- 不知道哪个环节慢
benchmark 后:
- DNS 解析: 100ms
- TTFB: 800ms
- 资源加载: 2100ms
结论:主要瓶颈在 TTFB,优化服务器响应
优化前后对比:
- 优化前: 3000ms
- 优化后: 800ms
- 提升: 73%
这就叫"有数据支撑的优化"
指标说明好的标准
P50中位数响应时间< 100ms
P9595%请求的响应时间< 200ms
P9999%请求的响应时间< 500ms
错误率失败请求占比< 0.1%
指标说明好的标准
FCPFirst Contentful Paint< 1.8s
LCPLargest Contentful Paint< 2.5s
TTFBTime To First Byte< 600ms
TTITime To Interactive< 3.8s
指标说明好的标准
查询时间单次查询耗时< 10ms
吞吐量QPS根据业务需求
连接池使用并发连接数< 80%
你想优化性能,但不知道从哪里开始
✅ 用 benchmark 跑一遍
→ 找到最慢的环节
→ 针对性优化
你做了一系列优化,想知道效果
✅ 用 benchmark 跑优化后
→ 和优化前对比
→ 量化提升
你在两个方案之间犹豫
✅ 用 benchmark 跑两个方案
→ 数据说话
→ 选择性能更好的
背景:用户反馈"搜索很慢"
1. 跑 benchmark
- 当前: P95 = 2000ms
2. 分析瓶颈
- 数据库查询: 1500ms
- 网络传输: 300ms
- 序列化: 200ms
3. 针对性优化
- 加索引: 1500ms → 50ms
4. 验证效果
- 优化后: P95 = 180ms
- 提升: 91%
背景:页面加载很慢
1. 用 lighthouse/performance 跑 benchmark
- LCP: 4.5s
- FCP: 2.8s
2. 分析
- 大图片: 2.3s
- JS 阻塞: 1.2s
3. 优化
- 压缩图片
- 代码分割
4. 验证
- LCP: 4.5s → 2.1s
- 提升: 53%
背景:你犹豫用 Redis 还是 Memcached
1. 准备测试环境
2. 跑 benchmark
- Redis: 10000 ops/s
- Memcached: 12000 ops/s
3. 选择 Memcached
Terminal window
# wrk
wrk -t12 -c400 -d30s http://localhost:3000/api
# autocannon
autocannon -c 100 -d 30 http://localhost:3000/api
# ab (Apache Bench)
ab -n 1000 -c 100 http://localhost:3000/api
Terminal window
# Lighthouse
lighthouse https://example.com --output=json
# WebPageTest
webpagetest test https://example.com
Terminal window
# MySQL
mysqlslap --concurrency=50 --iterations=10 --query="SELECT * FROM users"
# PostgreSQL
pgbench -c 10 -t 1000 mydb

核心指标

  • API: P50/P95/P99
  • 前端: LCP/FCP/TTI
  • DB: 查询时间/吞吐量

使用时机

  • 优化前找方向
  • 优化后验证效果
  • 方案选型对比

关键原则

  • 数据说话
  • 对比才有意义
  • 持续监控

查看源文件: GitHub原始文件