Go語(yǔ)言有一個(gè)非常棒的設(shè)計(jì)就是標(biāo)準(zhǔn)庫(kù)里面帶有代碼的性能監(jiān)控工具,在兩個(gè)地方有包:
net/http/pprof
runtime/pprof
其實(shí)net/http/pprof中只是使用runtime/pprof包來(lái)進(jìn)行封裝了一下,并在http端口上暴露出來(lái)
目前beego框架新增了pprof,該特性默認(rèn)是不開(kāi)啟的,如果你需要測(cè)試性能,查看相應(yīng)的執(zhí)行g(shù)oroutine之類的信息,其實(shí)Go的默認(rèn)包"net/http/pprof"已經(jīng)具有該功能,如果按照Go默認(rèn)的方式執(zhí)行Web,默認(rèn)就可以使用,但是由于beego重新封裝了ServHTTP函數(shù),默認(rèn)的包是無(wú)法開(kāi)啟該功能的,所以需要對(duì)beego的內(nèi)部改造支持pprof。
首先在beego.Run函數(shù)中根據(jù)變量是否自動(dòng)加載性能包
if PprofOn {
BeeApp.RegisterController(`/debug/pprof`, &ProfController{})
BeeApp.RegisterController(`/debug/pprof/:pp([\w]+)`, &ProfController{})
}
設(shè)計(jì)ProfConterller
package beego
import (
"net/http/pprof"
)
type ProfController struct {
Controller
}
func (this *ProfController) Get() {
switch this.Ctx.Params[":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)
}
通過(guò)上面的設(shè)計(jì),你可以通過(guò)如下代碼開(kāi)啟pprof:
beego.PprofOn = true
然后你就可以在瀏覽器中打開(kāi)如下URL就看到如下界面: http://wiki.jikexueyuan.com/project/go-web-programming/images/14.6.pprof.png" alt="" />
圖14.7 系統(tǒng)當(dāng)前goroutine、heap、thread信息
點(diǎn)擊goroutine我們可以看到很多詳細(xì)的信息:
http://wiki.jikexueyuan.com/project/go-web-programming/images/14.6.pprof2.png" alt="" />
圖14.8 顯示當(dāng)前goroutine的詳細(xì)信息
我們還可以通過(guò)命令行獲取更多詳細(xì)的信息
go tool pprof http://localhost:8080/debug/pprof/profile
這時(shí)候程序就會(huì)進(jìn)入30秒的profile收集時(shí)間,在這段時(shí)間內(nèi)拼命刷新瀏覽器上的頁(yè)面,盡量讓cpu占用性能產(chǎn)生數(shù)據(jù)。
(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
http://wiki.jikexueyuan.com/project/go-web-programming/images/14.6.pprof3.png" alt="" />
圖14.9 展示的執(zhí)行流程信息