14.6. pprof 支持
Go 语言有一个非常棒的设计就是标准库里面带有代码的性能监控工具,在两个地方有包:
net/http/pprof
runtime/pprof
其实 net/http/pprof 中只是使用 runtime/pprof 包来进行封装了一下,并在 http 端口上暴露出来
beego 支持 pprof
目前 beego 框架新增了pprof,该特性默认是不开启的,如果你需要测试性能,查看相应的执行 goroutine 之类的信息,其实 Go 的默认包 "net/http/pprof" 已经具有该功能,如果按照 Go 默认的方式执行 Web,默认就可以使用,但是由于 beego 重新封装了 ServHTTP函数,默认的包是无法开启该功能的,所以需要对 beego 的内部改造支持 pprof。
- 首先在 beego.Run 函数中根据变量是否自动加载性能包
if PprofOn {
BeeApp.RegisterController(`/debug/pprof`, &ProfController{})
BeeApp.RegisterController(`/debug/pprof/:pp([\w]+)`, &ProfController{})
}
- 设计 ProfController
package beego
import (
"net/http/pprof"
)
type ProfController struct {
Controller
}
func (this *ProfController) Get() {
switch this.Ctx.Param[":pp"] {
default:
pprof.Index(this.Ctx.ResponseWriter, this.Ctx.Request)
case "":
pprof.Index(this.Ctx.ResponseWriter, this.Ctx.Request)
case "cmdline":
pprof.Cmdline(this.Ctx.ResponseWriter, this.Ctx.Request)
case "profile":
pprof.Profile(this.Ctx.ResponseWriter, this.Ctx.Request)
case "symbol":
pprof.Symbol(this.Ctx.ResponseWriter, this.Ctx.Request)
}
this.Ctx.ResponseWriter.WriteHeader(200)
}
使用入门
通过上面的设计,你可以通过如下代码开启 pprof:
beego.PprofOn = true
然后你就可以在浏览器中打开如下 URL 就看到如下界面:
图 14.7 系统当前 goroutine、heap、thread 信息
点击 goroutine 我们可以看到很多详细的信息:
图 14.8 显示当前 goroutine 的详细信息
我们还可以通过命令行获取更多详细的信息
go tool pprof http://localhost:8080/debug/pprof/profile
这时候程序就会进入 30 秒的 profile 收集时间,在这段时间内拼命刷新浏览器上的页面,尽量让 cpu 占用性能产生数据。
(pprof) top10
Total: 3 samples
1 33.3% 33.3% 1 33.3% MHeap_AllocLocked
1 33.3% 66.7% 1 33.3% os/exec.(*Cmd).closeDescriptors
1 33.3% 100.0% 1 33.3% runtime.sigprocmask
0 0.0% 100.0% 1 33.3% MCentral_Grow
0 0.0% 100.0% 2 66.7% main.Compile
0 0.0% 100.0% 2 66.7% main.compile
0 0.0% 100.0% 2 66.7% main.run
0 0.0% 100.0% 1 33.3% makeslice1
0 0.0% 100.0% 2 66.7% net/http.(*ServeMux).ServeHTTP
0 0.0% 100.0% 2 66.7% net/http.(*conn).serve
(pprof)web
图 14.9 展示的执行流程信息