pprof 功能有2种开启方式,对应两种包:
- net/http/pprof:使用服务器的场景
- runtime/pprof:使用在非服务器应用程序的场景
这两个本质上是一致的,net/http/pporf 也只是在 runtime/pprof 上的一层 web 封装
pprof 支持四种类型的分析:
- CPU
CPU 分析,采样消耗 cpu 的调用,这个一般用来定位排查程序里耗费计算资源的地方。 - Memory
内存分析,一般用来排查内存占用,内存泄露等问题。 - Block
阻塞分析,会采样程序里阻塞的调用情况。 - Mutex
互斥锁分析,采样互斥锁的竞争情况。
一个简单的例子
package main
import (
"fmt"
"net/http"
_ "net/http/pprof"
)
var datas []string
func add(s string) []string {
datas = append(datas, s)
return datas
}
func main() {
go func() {
for {
fmt.Println(add("hello world"))
}
}()
http.ListenAndServe("0.0.0.0:6060", nil)
}
直接web访问:http://127.0.0.1:6060/debug/pprof/

需要注意的是:默认情况下是不会追踪 block 和 mutex 信息的,如果想要看这2个信息,需要在代码中加入:
runtime.SetBlockProfileRate(1) // 开启对阻塞操作的跟踪,block
runtime.SetMutexProfileFraction(1) // 开启对锁调用的跟踪,mutex
分析数据
通过网页看到的信息有限,更常规的做法是把数据下载下来,更专业的分析。
# 下载 cpu profile
go tool pprof http://127.0.0.1:6060/debug/pprof/profile
# 下载 heap profile
# go tool pprof http://47.93.238.9:8080/debug/pprof/heap
# 下载 goroutine profile
# go tool pprof http://47.93.238.9:8080/debug/pprof/goroutine
# 下载 block profile
# go tool pprof http://47.93.238.9:8080/debug/pprof/block
# 下载 mutex profile
# go tool pprof http://47.93.238.9:8080/debug/pprof/mutex
linux 下还可以使用:
# 这里以生成 trace.out 文件为例:
curl localhost:/debug/pprof/trace?seconds=30 > trace.out
运行上述命令将会让程序开始半分钟的cpu采样,并把内容保存到本地文件中:

接着我们可以输入一些命令,来获取一些信息:
-
top
列出cpu占用高的函数
image.png
-
traces
列出函数调用栈
参考资料
1、Go语言之pprof的性能调优
2、https://mp.weixin.qq.com/s/SvzMEdhxHfI9hYU62r1C7g
3、https://zhuanlan.zhihu.com/p/396363069
4、https://zhuanlan.zhihu.com/p/265080950
5、
网友评论