轻松入门Golang pprof实用不忽悠

401 阅读4分钟
原文链接: mp.weixin.qq.com

原文作者:shitaibin

来源:简书

网上已搜索golang pprof,资料不少,简明高效的一个没看到,这篇文章5步教你用会pprof获取cpu和内存prof。

第1步:安装易用的pprofgolang自带的prof包是runtime/pprof,这个是低级别的,需要你手动做一些设置等等周边工作,不利于我们快速上手,利用pprof帮助我们解决实际的问题。这里推荐davecheney封装的pprof,它可以1行代码,让你用上pprof,专心解决自己的代码问题,下载:

go get github.com/pkg/profile

第2步:安装graphvizpprof生成的prof文件时二进制的,需要把这个二进制的文件转换为我们人类可读的,graphviz可以帮助我们把二进制的prof文件转换为图像。Mac安装:

brew install graphviz

其他系统安装参考这里Graphviz Download。

第3步:修改你的main函数只需要为hi.go增加这一行,defer profile.Start().Stop(),程序运行时,默认就会记录cpu数据:

 1package main 2 3import ( 4    "fmt" 5    "github.com/pkg/profile" 6) 7 8func main() { 9    defer profile.Start().Stop()1011    sl := makeSlice()12    fmt.Printf("sum = %d\n", sumSlice(sl))13}1415func makeSlice() []int {16    sl := make([]int, 10000000)17    for idx := range sl {18        sl[idx] = idx19    }20    return sl21}2223func sumSlice(sl []int) int {24    sum := 025    for _, x := range sl {26        sum += x27    }28    return sum29}

第4步:编译运行你的函数编译和执行hi.go。

1go build hi.go2./hi

应当看到类似的结果,它输出了生成的cpu.pprof的路径:

12018/11/07 19:47:21 profile: cpu profiling enabled, /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile046201825/cpu.pprof2sum = 4999999500000032018/11/07 19:47:21 profile: cpu profiling disabled, /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile046201825/cpu.pprof

第5步:可视化prof可视化有多种方式,可以转换为text、pdf、svg等等。text命令是

1go tool pprof --text /path/to/yourbinary /var/path/to/cpu.pprof

结果是:

 1go tool pprof -text ./hi /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile046201825/cpu.pprof 2File: hi 3Type: cpu 4Time: Nov 7, 2018 at 7:47pm (CST) 5Duration: 202.18ms, Total samples = 50ms (24.73%) 6Showing nodes accounting for 50ms, 100% of 50ms total 7      flat  flat%   sum%        cum   cum% 8      40ms 80.00% 80.00%       40ms 80.00%  main.makeSlice /Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go 9      10ms 20.00%   100%       10ms 20.00%  main.sumSlice /Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go10         0     0%   100%       50ms   100%  main.main /Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go11         0     0%   100%       50ms   100%  runtime.main /usr/local/go/src/runtime/proc.go

还有pdf这种效果更好:

1go tool pprof --pdf /path/to/yourbinary /var/path/to/cpu.pprof > cpu.pdf

例子:

1go tool pprof -pdf ./hi /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile046201825/cpu.pprof > cpu.pdf

效果:

5步已经结束,你已经学会使用cpu pprof了吗?轻松获取内存ppfo如果你掌握了cpu pprof,mem pprof轻而易举就能拿下,只需要改1行代码:

1defer profile.Start(profile.MemProfile).Stop()

效果:

1go tool pprof -pdf ./hi /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile986580758/mem.pprof > mem.pdf


版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢。

Golang语言社区

ID:Golangweb

 www.GolangWeb.com

游戏服务器架构丨分布式技术丨大数据丨游戏算法学习