在程序中加上:
import (
_ "net/http/pprof"
)
go func() {
http.ListenAndServe("127.0.0.1:8888", nil)
}()
如果需要监听block阻塞情况:
runtime.SetBlockProfileRate(5 * 1000 * 1000) //采样频率,ns
监听锁事件:
// 当 rate = 0 时,关闭 mutex prof (默认值)
// 当 rate = 1 时,表示记录所有的 mutex event
// 当 rate > 1 时,记录 1/rate 的 mutex event(随机)
runtime.SetMutexProfileFraction(1)
浏览器查看:
打开浏览器访问 http://localhost:8888/debug/pprof/
命令行分析:
1. 安装Graphviz
brew install graphviz
2. cpu profiling:
go tool pprof http://localhost:8888/debug/pprof/profile
会生成pb.gz文件:
pprof.test.samples.cpu.001.pb.gz
可视化界面:
go tool pprof -http=":8081" pprof.test.samples.cpu.001.pb.gz
访问响应URL,即可查看火焰图
curl http://localhost:8081/ui/flamegraph > flamegraph.html
参考内存占用:
go tool pprof -alloc_space http://localhost:8888/debug/pprof/heap
可以使用参数指明分析的类型:
inuse_space — amount of memory allocated and not released yet
inuse_objects— amount of objects allocated and not released yet
alloc_space — total amount of memory allocated (regardless of released)
alloc_objects — total amount of objects allocated (regardless of released)
进入交互式模式之后,比较常用的有 top、list、traces、web 等命令。