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: 创建的线程信息;

image.png

通过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即可访问其火焰图

image.png

参考

1.https://studygolang.com/artic...
2.https://dave.cheney.net/high-...


a朋
63 声望39 粉丝