通过交互终端使用
# 下载 cpu profile,默认从当前开始收集 30s 的 cpu 使用情况,需要等待 30s
go tool pprof http://localhost:8888/debug/pprof/profile
# wait 120s
go tool pprof http://localhost:8888/debug/pprof/profile?seconds=120
# 下载 heap profile
go tool pprof http://localhost:8888/debug/pprof/heap
# 下载 goroutine profile
go tool pprof http://localhost:8888/debug/pprof/goroutine
# 下载 block profile
go tool pprof http://localhost:8888/debug/pprof/block
需要 runtime.SetBlockProfileRate(1) // 开启对阻塞操作的跟踪
# 下载 mutex profile
go tool pprof http://localhost:8888/debug/pprof/mutex
需要 runtime.SetMutexProfileFraction(1) // 开启对锁调用的跟踪
## 启动web页面
go tool pprof -http=0.0.0.0:8000 http://localhost:10217/debug/pprof/profile?seconds=120
## 分析已经生成好的文件
# 启动web页面
go tool pprof -http=0.0.0.0:8000 pprof.zone.alloc_objects.alloc_space.inuse_objects.inuse_space.003.pb.gz
# 命令行操作
go tool pprof pprof.zone.alloc_objects.alloc_space.inuse_objects.inuse_space.003.pb.gz
CPU分析
go tool pprof http://localhost:8888/debug/pprof/profile
内存占用分析
go tool pprof -sample_index=alloc_space http://localhost:8888/debug/pprof/heap
定位死锁和协程泄露
- 查看某条调用路径上,当前阻塞在此goroutine的数量
go tool pprof http://localhost:8888/debug/pprof/goroutine?debug=1
curl http://localhost:8888/debug/pprof/goroutine?debug=1 > /tmp/pprof1.txt
2. 查看所有goroutine的运行栈
go tool pprof http://localhost:8888/debug/pprof/goroutine?debug=2
curl http://localhost:8888/debug/pprof/goroutine?debug=2 > /tmp/pprof2.txt
使用heap发现内存问题
- 核查内存异常增长的问题
go tool pprof http://localhost:8888/debug/pprof/heap
pprof.demo2.001.pb.gz
pprof.demo2.002.pb.gz
使用base能够对比两个profile文件的差别,就像diff命令一样显示出增加和减少的变化
go tool pprof –base pprof.demo2.001.pb.gz pprof.demo2.002.pb.gz