Skip to main content

Go: 标准库 pprof

📅 2026-03-19 ✏️ 2026-03-19 Go 标准库 CS GO

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=30CPU profileseconds 采集时长
/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/goroutinegoroutine 栈debug=1 文本,debug=2 全栈
/debug/pprof/trace?seconds=5执行 tracego 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