Go pprof支持

2022-05-13 16:54 更新

Go語言有一個(gè)非常棒的設(shè)計(jì)就是標(biāo)準(zhǔn)庫里面帶有代碼的性能監(jiān)控工具,在兩個(gè)地方有包:

net/http/pprof
runtime/pprof

其實(shí)net/http/pprof中只是使用runtime/pprof包來進(jìn)行封裝了一下,并在http端口上暴露出來

beego支持pprof

目前beego框架新增了pprof,該特性默認(rèn)是不開啟的,如果你需要測試性能,查看相應(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)的包是無法開啟該功能的,所以需要對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)
}

使用入門

通過上面的設(shè)計(jì),你可以通過如下代碼開啟pprof:

beego.PprofOn = true

然后你就可以在瀏覽器中打開如下URL就看到如下界面: 

pprof支持 - 圖1

圖14.7 系統(tǒng)當(dāng)前goroutine、heap、thread信息

點(diǎn)擊goroutine我們可以看到很多詳細(xì)的信息:

pprof支持 - 圖2

圖14.8 顯示當(dāng)前goroutine的詳細(xì)信息

我們還可以通過命令行獲取更多詳細(xì)的信息

go tool pprof http://localhost:8080/debug/pprof/profile

這時(shí)候程序就會(huì)進(jìn)入30秒的profile收集時(shí)間,在這段時(shí)間內(nèi)拼命刷新瀏覽器上的頁面,盡量讓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

pprof支持 - 圖3

圖14.9 展示的執(zhí)行流程信息

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)