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) top
Showing nodes accounting for 1541.95kB, 100% of 1541.95kB total
Showing 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 onePassCopy
Total: 1.51MB
ROUTINE ======================== 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/heap
Fetching profile over HTTP from http://127.0.0.1:9999/debug/pprof/heap
Saved profile in /root/pprof/pprof.___go_build_main_go.alloc_objects.alloc_space.inuse_objects.inuse_space.003.pb.gz
Serving 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-…