Files
build-web-application-with-…/zh-tw/14.6.md
2019-02-26 01:40:54 +08:00

112 lines
3.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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?raw=true)
圖14.7 系統當前goroutine、heap、thread資訊
點選goroutine我們可以看到很多詳細的資訊
![](images/14.6.pprof2.png?raw=true)
圖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?raw=true)
圖14.9 展示的執行流程資訊
## links
* [目錄](<preface.md>)
* 上一節: [多語言支援](<14.5.md>)
* 下一節: [小結](<14.7.md>)