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{})
}
- 設計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)
}
使用入門
通過上面的設計,你可以通過如下代碼開啟pprof:
beego.PprofOn = true
我們可以通過命令列獲取更多詳細的資訊
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/259790.html
標籤:區塊鏈
