Beego pprof 性能分析工具使用

Jackey Golang 6,627 次浏览 , 没有评论

router.go 添加内容:

  1. beego.Router("/debug/pprof", &controllers.ProfController{})
  2. beego.Router("/debug/pprof/:app([\\w]+)", &controllers.ProfController{})

创建控制器:prof.go
添加内容:

  1. type ProfController struct {
  2. beego.Controller
  3. }
  4.  
  5. func (c *ProfController) Get() {
  6. switch c.Ctx.Input.Param(":app") {
  7. default:
  8. pprof.Index(c.Ctx.ResponseWriter, c.Ctx.Request)
  9. case "":
  10. pprof.Index(c.Ctx.ResponseWriter, c.Ctx.Request)
  11. case "cmdline":
  12. pprof.Cmdline(c.Ctx.ResponseWriter, c.Ctx.Request)
  13. case "profile":
  14. pprof.Profile(c.Ctx.ResponseWriter, c.Ctx.Request)
  15. case "symbol":
  16. pprof.Symbol(c.Ctx.ResponseWriter, c.Ctx.Request)
  17. }
  18. c.Ctx.ResponseWriter.WriteHeader(200)
  19. }

通过访问地址:http://127.0.0.1:8080/debug/pprof查看数据
注意:点击页面链接,如查看goroutine详情:http://127.0.0.1:8080/debug/goroutine?debug=1,会有问题,需将地址更改为:http://127.0.0.1:8080/debug/pprof/goroutine?debug=1。没搞明白啥原因。

如果想使用工具分析:
go tool pprof http://127.0.0.1:8080/debug/pprof/profile
需要安装:Graphviz 工具
下载地址:https://graphviz.gitlab.io/download/
生成视图命令:web

pprof 部分字段解析:

2 allocs # 所有过去内存分析采样
0 block # 导致同步原语阻塞的堆栈跟踪
0 cmdline # 程序启动参数
4 goroutine # 所有当前goroutine堆栈跟踪
2 heap # 活动对象内存分配采样
0 mutex # 互斥锁跟踪
0 profile # 生成cpuprofile文件 生成文件使用go tool pprof工具分析
8 threadcreate # 创建系统线程的堆栈跟踪
0 trace # 对当前程序执行的跟踪 生成文件使用go tool trace工具分析
full goroutine stack dump # 显示所有goroutine的堆栈

生成火焰图

  1. 安装 go-torch
    go get -v github.com/uber/go-torch
  2. 安装FlameGraph
    git clone https://github.com/brendangregg/FlameGraph.git
    将FlameGraph目录加入到操作系统的环境变量中。
  3. 使用命令生成火焰图
    go-torch -u http://127.0.0.1:8080 -t 30
    30秒之后终端会初夏如下提示:Writing svg to torch.svg
    用浏览器打开就可以看到详细信息。

火焰图的y轴表示cpu调用方法的先后,x轴表示在每个采样调用时间内,方法所占的时间百分比,越宽代表占据cpu时间越多。通过火焰图我们就可以更清楚的找出耗时长的函数调用,然后不断的修正代码,重新采样,不断优化。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Go