四类 profile#
| Profile | 默认采样率 | 看什么 |
|---|---|---|
| CPU | 100Hz | 哪些代码在消耗 CPU |
| heap | 512KB | 内存分配与存活 |
| goroutine | 100% | goroutine 状态与阻塞点 |
| goroutineleak | GC 触发 | 永久阻塞的 goroutine(Go 1.27 正式可用) |
| block | 100% | channel / mutex 阻塞时长 |
| mutex | 100% | 锁竞争时长 |
| threadcreate | — | 线程创建 |
采集方式#
HTTP 端点#
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
// 绑定到独立端口,且只监听本地,避免被外部访问
http.ListenAndServe("127.0.0.1:6060", nil)
}()
// ... 业务服务
}注意:net/http/pprof 注册到 DefaultServeMux,所以要用 http.DefaultServeMux 启动,或者显式注册:
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)安全提醒:pprof 端点能触发 CPU 尖峰、阻塞所有 goroutine(goroutine profile 的 debug=2)甚至下载可执行文件。绝不能暴露到公网,也不要放在反向代理后面不加限制。
命令行采集#
# CPU profile,30 秒
go test -cpuprofile=cpu.out ./...
go tool pprof -top cpu.out
# 内存 profile
go test -memprofile=mem.out -bench=. ./...
go tool pprof -top -sample_index=alloc_space mem.out
# 阻塞 profile
go test -blockprofile=block.out ./...
go tool pprof -top block.out
# goroutine profile
go test -goroutineprofile=goroutine.out ./...分析 pprof#
go tool pprof cpu.out进入交互模式后:
(pprof) top # 按耗时排序
(pprof) top -cum # 按累计耗时排序
(pprof) list FuncName # 逐行看某个函数
(pprof) web # 生成 SVG 火焰图
(pprof) peek FuncName # 谁调用了它
(pprof) traces # 追踪调用链
(pprof) quit直接生成火焰图#
go tool pprof -http=:8080 cpu.out会启动一个 Web 界面,包含 Flame Graph、Top、Source、Peek 等视图。
常用命令#
# 前 20 个函数
go tool pprof -top -nodecount=20 cpu.out
# 只看累计
go tool pprof -top -cum cpu.out
# 按正则过滤
go tool pprof -top -focus='database' cpu.out
# 排除某些路径
go tool pprof -top -ignore='runtime\.' cpu.out
# 导出为 SVG
go tool pprof -svg cpu.out > flame.svg怎么读火焰图#
- 宽度 = 该栈帧占用的 CPU 时间比例(按调用栈聚合)
- 高度 = 调用栈深度
- 宽而扁的帧 = 热点函数
- 宽而高的块 = 深度调用链,可能有不必要的嵌套
火焰图是「聚合后的调用栈」,一个宽的块可能来自成千上万个不同的调用点。
goroutineleak:专门抓泄漏的 profile#
Go 1.27 起,goroutineleak profile 正式可用:
curl -o leak.out http://localhost:6060/debug/pprof/goroutineleak
go tool pprof -top leak.out它和普通的 goroutine profile 不是一回事:
| goroutine profile | goroutineleak profile | |
|---|---|---|
| 列出内容 | 所有 goroutine | 永远醒不过来的那些 |
| 判定方式 | 快照当前所有 goroutine | 借助 GC 可达性分析判断「阻塞原语不可达」 |
| 运行时开销 | 需要采样 | 不采样时为零(由 GC 顺带完成) |
原理是:如果 goroutine G 阻塞在并发原语 P 上,而 P 从任何可运行 goroutine 都不可达,那 P 永远不会被解锁,G 就永远醒不过来。
局限:因为依赖可达性,通过全局变量可达的阻塞原语可能识别不出来。它抓不到「逻辑上死锁但原语仍可达」的情况。
Go 1.26:pprof 的 Web UI 默认打开火焰图#
go tool pprof -http=:8080 现在默认直接进入火焰图视图,不用再从菜单里切一次。旧的其他视图仍然保留在菜单里。
区分「自己写的代码」和「runtime」#
go tool pprof -top -ignore='runtime|gc' cpu.out如果大量时间在 runtime.mallocgc 和 runtime.gcBgMarkWorker,说明是内存分配压力导致的,应转向优化分配。
Benchmark#
func BenchmarkParse(b *testing.B) {
data := []byte(`{"name":"go"}`)
for i := 0; i < b.N; i++ {
var v Config
if err := json.Unmarshal(data, &v); err != nil {
b.Fatal(err)
}
}
}go test -bench=. -benchmem ./...输出:
BenchmarkParse-8 1000000 1123 ns/op 256 B/op 4 allocs/op四列含义:
1123 ns/op—— 每次迭代耗时256 B/op—— 每次迭代分配的字节数4 allocs/op—— 每次迭代的分配次数
-benchmem 应该成为默认选项,它提供的信息比时间更有价值。
测试产物目录(Go 1.26+)#
Go 1.26 给 testing.T / testing.B / testing.F 加了 ArtifactDir(),可以往里面写调试用的文件(堆快照、日志、profiling 输出),CI 会在测试结束后统一收集。
func TestWithArtifact(t *testing.T) {
dir := t.ArtifactDir()
if err := os.WriteFile(filepath.Join(dir, "app.log"), []byte("debug log"), 0644); err != nil {
t.Fatal(err)
}
}命令行开关:
go test -v -artifacts -outputdir=/tmp/out ./...每个子测试有独立的产物目录(_artifacts/<包>/<测试>/<随机后缀>),不会互相覆盖。
go test 会自动跑 stdversion 检查(Go 1.27+)#
Go 1.27 起,go test 默认启用 stdversion vet 检查:报告使用了比该文件 go 指令更新的标准库符号。
// go.mod 里写的是 go 1.24
// 但代码里用了 Go 1.26 才有的 API
ptr := new(int64(300)) // stdversion: new with an argument requires go1.26 or later这解决了一个长期存在的痛点:旧模块在新工具链上编译时,因为标准库新 API 而意外用上了新语义。它和 go test 一起跑,等于免费获得了一层「最低版本一致性」检查。
基准测试的正确姿势#
// ✅ 避免编译器优化掉
var result int
func BenchmarkLoop(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
result = compute(i)
}
}把结果赋给包级变量,防止编译器发现结果没被使用而把整个计算删掉。
基准测试的常见错误#
1. 每次迭代都 setup
// ❌ 把 setup 算进了耗时
func BenchmarkBad(b *testing.B) {
for i := 0; i < b.N; i++ {
data := prepare() // 每次都重新准备
process(data)
}
}
// ✅
func BenchmarkGood(b *testing.B) {
data := prepare()
b.ResetTimer()
for i := 0; i < b.N; i++ {
process(data)
}
}2. 没有并行基准
func BenchmarkParallel(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
// ...
}
})
}go test -bench=. -cpu=1,2,4,8 ./...-cpu 指定 GOMAXPROCS 的值,衡量扩展性。
3. 结果不显著
单次运行的数字波动很大。用 benchstat 做统计比较:
# 安装
go install golang.org/x/perf/cmd/benchstat@latest
# 采集多次
go test -bench=. -count=10 -run=^$ > old.txt
# ... 修改代码 ...
go test -bench=. -count=10 -run=^$ > new.txt
# 比较
benchstat old.txt new.txt输出:
│ old.txt │ new.txt │
│ sec/op │ sec/op vs base │
Parse-8 1123.5n ± 2% 892.1n ± 1% -20.56% (p=0.000 n=10)带 ± 和 p=0.000 才是统计显著的结论。
基准测试的陷阱#
- 微基准 ≠ 真实负载:缓存全命中、CPU 频率、CPU 亲和性都会影响
- 逃逸分析要单独看:
go test -bench=. -benchmem -gcflags='-m' ./... 2>&1 | grep escape运行时 trace#
runtime/trace 记录 goroutine 调度、GC、网络等事件:
import "runtime/trace"
func main() {
f, _ := os.Create("trace.out")
trace.Start(f)
defer trace.Stop()
// ... 业务逻辑
}go tool trace trace.outWeb 界面能看到:
- Goroutine analysis:每个 goroutine 的执行时间线
- Scheduler latency profile:调度延迟分布
- Sync blocking profile:channel / mutex 阻塞
- Syscall blocking profile:系统调用阻塞
- GC view:GC 暂停时间线
排查「延迟尖刺」时 trace 比 CPU profile 更有效,因为 CPU profile 看不到「goroutine 等了 50ms 才被调度上」这类问题。
优化流程#
第 0 步:先定义指标#
「程序慢」不是可执行的指标。要明确:
- 是 p99 延迟高,还是平均延迟高?
- 吞吐量不够还是单次操作慢?
- CPU 打满了还是内存压力大?
不同答案指向完全不同的优化方向。
第 1 步:建立基线#
go test -bench=BenchmarkHot -benchmem -count=10 -run=^$ > base.txt第 2 步:找到热点#
go tool pprof -http=:8080 cpu.out只看一个 profile 是不够的:
- CPU 高 → 看 CPU profile
- 内存高 → 看 heap 的
inuse_space - 延迟尖刺 → 看 trace
- 并发问题 → 看 block/mutex profile
第 3 步:优化#
常见有效的优化手段,按性价比排序:
- 减少分配(
allocs/op降下来通常直接见效) - 升级到 Go 1.26 / 1.27(Green Tea GC + 尺寸特化分配,有时一步到位)
- 避免不必要的反射和 interface{}
- 用
sync.Pool复用大对象 - 批量化:把 1000 次单条写合并成 1 次批量写
- 减少拷贝:避免大结构体按值传递
- 加缓存:注意缓存一致性和雪崩
- 换算法:O(n²) → O(n log n)
第 4 步:验证#
go test -bench=. -count=10 -run=^$ > after.txt
benchstat base.txt after.txt同时跑 go test -race ./...,确认没有引入数据竞争。
常见性能问题速查#
| 症状 | 可能原因 | 排查 |
|---|---|---|
| CPU 100% | 忙循环、死锁自旋 | CPU profile |
| 内存持续增长 | 泄漏、goroutine 泄漏 | heap inuse_space + goroutine profile |
| GC 频繁 | 分配速率高 | heap alloc_space + gctrace |
| 延迟毛刺 | GC STW、调度延迟、锁竞争 | trace + block/mutex profile |
| 吞吐上不去 | 串行瓶颈、连接池太小 | CPU profile + 火焰图 |
| 偶发超时 | goroutine 泄漏、channel 阻塞 | goroutine profile |
小结#
- pprof 四类 profile 各有用途,先明确问题类型再采集
-benchmem提供分配数据,通常比时间更能说明问题- 用
benchstat做统计显著性判断,不要凭一次运行的数字下结论 - 延迟问题用
runtime/trace,CPU 问题用 pprof - 优化流程是「定义指标 → 基线 → 剖析 → 改动 → 验证」,不要跳过任何一步