golang pprof
Alex 4/3/2023 golang
# 开启 pprof
相当于导入了 pprof 的 init 函数,由于导入是深度优先原则,所以 pprof 的 init 会被先执行,后续当前包内的 init 函数执行后会为其建立 http 监听。
package main
import (
"net/http"
_ "net/http/pprof"
)
func init() {
go func() {
_ = http.ListenAndServe("localhost:6060", nil)
}()
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
net/http/pprof 包的 init,注册了5个路由
func init() {
http.HandleFunc("/debug/pprof/", Index)
http.HandleFunc("/debug/pprof/cmdline", Cmdline)
http.HandleFunc("/debug/pprof/profile", Profile)
http.HandleFunc("/debug/pprof/symbol", Symbol)
http.HandleFunc("/debug/pprof/trace", Trace)
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 预览
打开 http://localhost:6060/debug/pprof/ 即可
以 goroutine 为例,url 为 http://localhost:6060/debug/pprof/goroutine?debug=1
, 与源码中注册的路由一致。
默认为网页展示模式,我们也可以去掉 url 中 ?debug=1
来访问,将会得到一个文件。
# 简单的数据分析
分析刚才得到的文件,将会进入交互式分析控制台
go tool pprof goroutine
1
如果监听了公网,则也可以直接分析远程文件
go tool pprof http://hostname:6060/debug/pprof/goroutine
1
生成 svg
go tool pprof -svg goroutine >goroutine.svg
1
打开 web 网站进行图形化查看
go tool pprof --http=:6060 goroutine
1