# 14.6 pprof 支援 Go 語言有一個非常棒的設計就是標準函式庫裡面帶有程式碼的效能監聽工具,在兩個地方有套件: ```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 函式中根據變數是否自動載入效能套件 ```Go if PprofOn { BeeApp.RegisterController(`/debug/pprof`, &ProfController{}) BeeApp.RegisterController(`/debug/pprof/:pp([\w]+)`, &ProfController{}) } ``` - 設計 ProfController ```Go 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: ```Go beego.PprofOn = true ``` 然後你就可以在瀏覽器中開啟如下 URL 就看到如下介面: ![](images/14.6.pprof.png) 圖 14.7 系統當前 goroutine、heap、thread 資訊 點選 goroutine 我們可以看到很多詳細的資訊: ![](images/14.6.pprof2.png) 圖 14.8 顯示當前 goroutine 的詳細資訊 我們還可以透過命令列取得更多詳細的資訊 ```Go 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 ![](images/14.6.pprof3.png) 圖 14.9 展示的執行流程資訊 ## links * [目錄]() * 上一節:[多語言支援](<14.5.md>) * 下一節:[小結](<14.7.md>)