Go: 标准库 pprof
Outlinks (0)
No outlinks found
Backlinks (1)
Backlinks (1)
1 · 标准库 pprof#
pprof 通过采样回答 程序的时间/内存/锁花在哪了。
每条采样 = 调用栈(谁触发的,定位到函数/行号)+ 事件的度量值(花了多少)。
- 事件:运行时发生的特定动作——占用 CPU、分配内存、阻塞在锁/channel 上等。
- 度量:对事件的量化——持续了多久(时间)、分配了多少(字节/对象数)、发生了几次(计数)。
- 调用栈:记录事件发生时的函数调用链,用于定位”是哪段代码导致的”。
Go 提供两个 pprof 包(runtime/pprof + net/http/pprof),用于生成 go tool pprof 可视化工具所需格式的性能剖析数据。
每种 profile 采样的事件与度量:
| Profile | 采样内容 | 采样方式 | 度量值 |
|---|---|---|---|
| cpu | 每个函数占用的 CPU 时间 | 定时信号(默认 100Hz,每 10ms) | 时间 |
| heap | 活跃对象的内存分配点(最近一次 GC 后) | 内存分配采样(默认每 512KB) | 字节/对象数(默认 -inuse_space) |
| allocs | 同 heap,但默认展示累计分配(含已 GC) | 同上 | 字节/对象数(默认 -alloc_space) |
| block | 阻塞在同步原语上的时间(Mutex/RWMutex/WaitGroup/Cond/channel) | 时间采样,runtime.SetBlockProfileRate 控制 | 累计阻塞时间 |
| mutex | 互斥锁竞争(unlock 时其他 goroutine 累计等待时间) | 事件采样,runtime.SetMutexProfileFraction 控制 | 累计等待时间 |
| goroutine | 所有当前 goroutine 的栈 | 全量快照 | 数量 |
| threadcreate | 导致创建新 OS 线程的栈 | 全量记录 | 数量 |
CPU profile 有独立 API(
StartCPUProfile/StopCPUProfile),因为它是流式写入;其余均通过pprof.Lookup(name)获取。
1.1 · 1. 开始(接入)#
- go test 内置(零代码)
go test -cpuprofile cpu.prof -memprofile mem.prof -bench .
- runtime/pprof 编程式
import "runtime/pprof"
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
- net/http/pprof HTTP 端点(推荐线上服务)
import _ "net/http/pprof" // 副作用注册 /debug/pprof/*(Go 1.22 起仅 GET)
// 若无现有 HTTP server:
go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }()
1.2 · 2. 采集#
- runtime/pprof 核心 API
| 函数 | 用途 |
|---|---|
StartCPUProfile(w) / StopCPUProfile() | CPU profile |
WriteHeapProfile(w) | 堆内存 profile |
Lookup(name).WriteTo(w, 0) | 按名称采集(allocs, heap, block, mutex, goroutine, threadcreate) |
NewProfile(name) / Profiles() | 自定义 profile |
Labels / WithLabels / Do | 给 goroutine 打标签,便于按维度筛选 |
// 内存:allocs 类似 go test -memprofile; heap 默认 inuse_space
runtime.GC()
pprof.Lookup("allocs").WriteTo(f, 0)
- net/http/pprof 端点
| 端点 | 说明 | 参数 |
|---|---|---|
/debug/pprof/profile?seconds=30 | CPU profile | seconds 采集时长 |
/debug/pprof/heap?gc=1 | 堆内存 | gc=1 先触发 GC;seconds 返回 delta |
/debug/pprof/allocs | 累计分配 | seconds 返回 delta |
/debug/pprof/block | 阻塞 | 需 runtime.SetBlockProfileRate |
/debug/pprof/mutex | 锁竞争 | 需 runtime.SetMutexProfileFraction |
/debug/pprof/goroutine | goroutine 栈 | debug=1 文本,debug=2 全栈 |
/debug/pprof/trace?seconds=5 | 执行 trace | 用 go tool trace 分析 |
debug=N:0 二进制(默认),>0 纯文本。
1.3 · 3. 分析#
# 从 HTTP 端点直接分析
go tool pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
# 从本地文件分析
go tool pprof cpu.prof
交互模式常用命令:top(热点排名)、list func(源码级标注)、web(调用图)、peek(上下游)。
# execution trace
curl -o trace.out http://localhost:6060/debug/pprof/trace?seconds=5
go tool trace trace.out