go-doc-pprof

安装pprof

golang自带的prof包是runtime/pprof,这个是低级别的,不怎么好用

1
go get github.com/pkg/profile

安装graphviz

pprof生成的prof文件时二进制的,需要把这个二进制的文件转换为我们人类可读的,graphviz可以帮助我们把二进制的prof文件转换为图像(不是必须,需要图形化的可以安装)

graphviz官网

使用

main 函数一开始加上

1
2
3
4
5
6
7
8
9
10
# 进行cpu数据采样
defer profile.Start().Stop()

# 进行内存数据采样
defer profile.Start(profile.MemProfile).Stop()

# 其他的
MutexProfile
BlockProfile
TraceProfile

编译运行

1
2
go build xxx.go
./xxx.go

数据查看

1
2
3
4
5
# 文本方式参考
go tool pprof --text ./ C:\Users\BoBo\AppData\Local\Temp\profile352988711\cpu.pprof

# pdf方式参考
go tool pprof -pdf ./ C:\Users\BoBo\AppData\Local\Temp\profile352988711\cpu.pprof > cpu.pdf

列描述

flat:函数在 CPU 上运行的时间
flat%:函数在CPU上运行时间的百分比
sum%:是从第一行到当前行所有函数累加使用 CPU 的比例,如第二行sum=53.85=30.77+23.08
cum:这个函数以及子函数运行所占用的时间,应该大于等于flat
cum%:这个函数以及子函数运行所占用的比例,应该大于等于flat%
最后一列:函数的名字