golang pprof 使用

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。 

golang pprof 使用

2013-11-16 19:58 712人閱讀 評論(0) 收藏 舉報

目錄(?)[+]

轉自:http://www.cnblogs.com/yjf512/archive/2012/12/27/2835331.html

go中有pprof包來做代碼的效能監控,在兩個地方有包:

net/http/pprof

runtime/pprof

其實net/http/pprof中只是使用runtime/pprof包來進行封裝了一下,並在http連接埠上暴露出來

pprof包

網頁伺服器

如果你的go程式是用http包啟動的web伺服器,你想查看自己的web伺服器的狀態。這個時候就可以選擇net/http/pprof。你只需要引入包_"net/http/pprof",然後就可以在瀏覽器中使用http://localhost:port/debug/pprof/直接看到當前web服務的狀態,包括CPU佔用情況和記憶體使用量情況等。具體使用方式你可以看godoc的說明。

服務進程

如果你的go程式不是web伺服器,而是一個服務進程,那麼你也可以選擇使用net/http/pprof包,同樣引入包net/http/pprof,然後在開啟另外一個goroutine來開啟連接埠監聽。

比如:

go func() {        log.Println(http.ListenAndServe("localhost:6060", nil)) 

}()

應用程式

如果你的go程式只是一個應用程式,比如計算fabonacci數列,那麼你就不能使用net/http/pprof包了,你就需要使用到runtime/pprof。具體做法就是用到pprof.StartCPUProfile和pprof.StopCPUProfile。比如下面的例子:

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")func main() {    flag.Parse()    if *cpuprofile != "" {        f, err := os.Create(*cpuprofile)        if err != nil {            log.Fatal(err)        }        pprof.StartCPUProfile(f)        defer pprof.StopCPUProfile()    }

運行程式的時候加一個--cpuprofile參數,比如fabonacci --cpuprofile=fabonacci.prof

這樣程式啟動並執行時候的cpu資訊就會記錄到XXX.prof中了。

下一步就可以使用這個prof資訊做出效能分析圖了(需要安裝graphviz)。

使用go tool pprof (應用程式) (應用程式的prof檔案)

進入到pprof,使用web命令就會在/tmp下產生svg檔案,svg檔案是可以在瀏覽器下看的。像這個樣子:

如果你的程式非常簡單,比如只有println一個語句,你用pprof.StartCPUProfile是列印不出任何東西的。

舉例

下面拿go-tour舉個例子,這是個web程式,我在代碼中加入了

_ "net/http/pprof"

在瀏覽器中我就可以直接看prof資訊了

產生CPU狀態分析圖

下面我們想要產生CPU狀態分析圖,調用go tool pprof http://localhost:3999/debug/pprof/profile

就會進入30秒的profile收集時間,在這段事件內猛重新整理點擊go-tour瀏覽器上的頁面,盡量讓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

  • 上一篇Mac OS X shell 顏色配置
  • 下一篇DFA演算法過濾敏感詞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.