pprof是golang提供的排查go利用程序运行状况的调试工具,能够查看运行的goroutine、以后内存对象及其占用状况等。当发现过程内存占用过高、CPU使用率过高时,通过pprof能够帮忙排查应用程序的问题。
pprof仅记录heap内存,未记录stack内存;pprof是基于采样的,默认每1000次内存调配,执行1次ppof。
pprof能够帮忙发现内存问题,但不肯定发现内存泄露问题,还须要联合业务代码和监控指标综合剖析。
pprof配置应用
import ( "github.com/DeanThompson/ginpprof" "github.com/gin-gonic/gin" "net/http")func StartHttp() { r := gin.Default() ginpprof.Wrap(r) r.GET("/index", func(c *gin.Context) { c.JSON(http.StatusOK, "index") }) r.Run(":9999")}
通过监听的9999拜访web页面:
- goroutine: goroutine数量及栈信息;
- heap: 堆中的内存对象信息;
- threadcreate: 创立的线程信息;
通过go tool pprof可剖析其内存占用统计:
# go tool pprof http://192.168.1.1:9999/debug/pprof/heap(pprof) topShowing nodes accounting for 1541.95kB, 100% of 1541.95kB totalShowing top 10 nodes out of 12 flat flat% sum% cum cum% 516.01kB 33.46% 33.46% 1541.95kB 100% github.com/go-playground/validator/v10.init 513.31kB 33.29% 66.75% 513.31kB 33.29% regexp.onePassCopy 512.62kB 33.25% 100% 512.62kB 33.25% regexp/syntax.(*compiler).inst (inline) 0 0% 100% 1025.94kB 66.54% regexp.Compile (inline)
能够通过top查看占用最高的内存对象,通过list查看相应的代码:
(pprof) list onePassCopyTotal: 1.51MBROUTINE ======================== regexp.onePassCopy in /usr/local/go/src/regexp/onepass.go 513.31kB 513.31kB (flat, cum) 33.29% of Total . . 220:// onePassCopy creates a copy of the original Prog, as we'll be modifying it . . 221:func onePassCopy(prog *syntax.Prog) *onePassProg { . . 222: p := &onePassProg{ . . 223: Start: prog.Start, . . 224: NumCap: prog.NumCap, 513.31kB 513.31kB 225: Inst: make([]onePassInst, len(prog.Inst)), . . 226: } . . 227: for i, inst := range prog.Inst { . . 228: p.Inst[i] = onePassInst{Inst: inst} . . 229: } . . 230:
pporf生成火焰图
# go tool pprof -http=127.0.0.1:6071 http://192.168.1.1:9999/debug/pprof/heapFetching profile over HTTP from http://127.0.0.1:9999/debug/pprof/heapSaved profile in /root/pprof/pprof.___go_build_main_go.alloc_objects.alloc_space.inuse_objects.inuse_space.003.pb.gzServing web UI on http://127.0.0.1:6071
拜访http://127.0.0.1:6071,VIEW-->Flame Graph即可拜访其火焰图
参考
1.https://studygolang.com/artic...
2.https://dave.cheney.net/high-...