Skip to content
Go
pprof — 性能分析

pprof — 性能分析

pprof 是 Go 内置的性能剖析工具,无需第三方依赖即可分析 CPU、内存、Goroutine 等。


1. 采样类型一览

类型 采样内容 适用场景
CPU profile 函数 CPU 时间 找出热点函数
Heap profile 堆内存分配 内存泄漏、高分配
Alloc profile 历史累计分配 找出分配最多的代码
Goroutine profile Goroutine 堆栈 排查泄漏
Block profile 阻塞在锁上的时间 锁竞争
Mutex profile 互斥锁争用 锁争用分析

2. 两种使用方式

方式 1:HTTP 端点(推荐生产)

import _ "net/http/pprof"

func main() {
    go func() {
        // 在内部端口或 localhost 上暴露
        log.Println(http.ListenAndServe("localhost:6060", nil))
    }()
    // ... 业务代码
}

端点:

http://localhost:6060/debug/pprof/           # 总览
http://localhost:6060/debug/pprof/profile    # 30s CPU profile
http://localhost:6060/debug/pprof/heap       # 堆快照
http://localhost:6060/debug/pprof/goroutine  # goroutine 堆栈
http://localhost:6060/debug/pprof/block      # 阻塞事件
http://localhost:6060/debug/pprof/mutex      # 互斥锁事件

💡 安全规范:pprof 端点绝不对公网暴露,使用内部端口或 IP 白名单。

方式 2:代码内直接写入文件

import "runtime/pprof"

func main() {
    f, _ := os.Create("cpu.pprof")
    pprof.StartCPUProfile(f)
    defer pprof.StopCPUProfile()

    // 被分析的代码
    doWork()

    // 堆快照
    f2, _ := os.Create("heap.pprof")
    pprof.WriteHeapProfile(f2)
    f2.Close()
}

3. 分析 profile 文件

# 交互式分析
go tool pprof cpu.pprof

# 常用交互命令
# top 10        — 显示最消耗的 10 个位置
# list 函数名    — 显示函数源码及每行耗时
# web           — 生成调用图(需要 graphviz)
# pdf           — 生成 PDF 报告
# peek 函数名    — 查看函数调用上下文
# tree          — 树状调用图

# 直接生成图表
go tool pprof -svg cpu.pprof > cpu.svg
go tool pprof -http :8080 cpu.pprof  # 浏览器交互

# 对比两个 profile
go tool pprof -base old.pprof new.pprof

内存分析重点

go tool pprof -alloc_space heap.pprof   # 累计分配(找出分配最多的代码)
go tool pprof -inuse_space heap.pprof   # 当前在用(找出内存泄漏)

4. 启用阻塞和互斥锁分析

import "runtime"

func init() {
    runtime.SetBlockProfileRate(1)    // 记录所有阻塞事件
    runtime.SetMutexProfileFraction(1) // 记录所有互斥锁事件
}

性能提示:这些分析有一定开销,建议仅在排查问题时临时开启。


5. 🔬 典型分析流程

CPU 热点排查

# 1. 采集 CPU profile
curl -o cpu.pprof http://localhost:6060/debug/pprof/profile?seconds=30

# 2. 查看 top 函数
go tool pprof -top cpu.pprof

# 3. 定位具体代码行
go tool pprof -list funcName cpu.pprof

# 4. 看调用图
go tool pprof -web cpu.pprof

内存泄漏排查

# 1. 采集两个时间点的 heap
curl -o heap1.pprof http://localhost:6060/debug/pprof/heap
# ... 运行一段时间 ...
curl -o heap2.pprof http://localhost:6060/debug/pprof/heap

# 2. 对比差异
go tool pprof -base heap1.pprof heap2.pprof

# 3. 查看增长最多的
(pprof) top