Go | pprof
1. 简介
Go语言性能分析工作,通过HTTP接口来分析内存、CPU占用锁冲突问题等。
2. 服务端
Go默认HTTP Server
package main
import (
"log"
"net/http"
// net/http/pprof包中init方法注册路由
_ "net/http/pprof"
)
func main() {
log.Println(http.ListenAndServe(":6060", nil))
}
gin框架
package main
import (
"github.com/gin-gonic/gin"
"net/http/pprof"
)
func main() {
r := gin.Default()
r.GET("/debug/pprof/:name", func(c *gin.Context) {
pprof.Index(c.Writer, c.Request)
})
r.GET("/debug/pprof/cmdline", func(c *gin.Context) {
pprof.Cmdline(c.Writer, c.Request)
})
r.GET("/debug/pprof/profile", func(c *gin.Context) {
pprof.Profile(c.Writer, c.Request)
})
r.GET("/debug/pprof/symbol", func(c *gin.Context) {
pprof.Symbol(c.Writer, c.Request)
})
r.GET("/debug/pprof/trace", func(c *gin.Context) {
pprof.Trace(c.Writer, c.Request)
})
r.Run(":6060") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
3. 客户端
3.1. 准备
需要提前安装graphviz,下面演示macOS安装方法
macOS:
brew install graphviz
3.2. 拉取和加载信息
下面两种方法都可以
使用命令直接查看
# 分析内存占用
go tool pprof http://localhost:6060/debug/pprof/heap
# 分析CPU占用
go tool pprof http://localhost:6060/debug/pprof/profile
将信息拉取到本地在查看
# 拉取内存信息
wget -O heap.out http://localhost:6060/debug/pprof/heap
# 加载信息(交互式命令)
go tool pprof heap.out
3.3. 查看信息
注意当前已进入go tool pprof命令交互
查看占用内存最多10个
(pprof) top 10
Showing nodes accounting for 3586.70kB, 100% of 3586.70kB total
Showing top 10 nodes out of 37
flat flat% sum% cum cum%
513.31kB 14.31% 14.31% 513.31kB 14.31% regexp/syntax.(*compiler).inst (inline)
512.56kB 14.29% 28.60% 512.56kB 14.29% runtime.allocm
512.50kB 14.29% 42.89% 512.50kB 14.29% regexp.makeOnePass
512.20kB 14.28% 57.17% 512.20kB 14.28% runtime.malg
512.05kB 14.28% 71.45% 512.05kB 14.28% regexp/syntax.simplify1 (inline)
512.05kB 14.28% 85.72% 512.05kB 14.28% text/template/parse.(*lexer).emit
512.02kB 14.28% 100% 512.02kB 14.28% text/template/parse.(*Tree).newList (inline)
0 0% 100% 1537.87kB 42.88% github.com/go-playground/validator/v10.init
0 0% 100% 512.02kB 14.28% html/template.(*Template).Parse
0 0% 100% 512.02kB 14.28% net/rpc.init
在网页已查看图示
(pprof) web
查看更多命令
(pprof) help
输出内容太多省略