pprof 是 Go 内置的性能分析工具,可以分析 CPU 使用、内存分配、goroutine 阻塞和互斥锁竞争。它是定位性能瓶颈的第一利器。
启用 pprof
import _ "net/http/pprof"
// 在单独的 goroutine 中启动
go func() {
log.Println(http.ListenAndServe(":6060", nil))
}()
四种分析类型
- CPU Profile:记录函数调用频率和耗时。精准定位 CPU 热点。
- Heap Profile:内存分配位置和大小。追踪内存泄漏和过度分配。
- Goroutine Profile:所有 goroutine 的栈信息,排查 goroutine 泄漏。
- Mutex Profile:锁竞争分析,找出争用严重的锁。
分析命令
# 交互式分析
go tool pprof http://localhost:6060/debug/pprof/heap
# 火焰图
go tool pprof -http=:8080 http://localhost:6060/debug/pprof/profile?seconds=30
常见优化目标
- 频繁的内存分配(GC 压力大)→ 对象池、预分配。
- 锁竞争导致阻塞 → 缩小锁粒度、无锁数据结构。
- goroutine 不可控增长 → 使用 worker pool 限制并发。
没有测量的优化就是盲目猜测。pprof 让你看见程序的真实行为。