1. 程式人生 > >golang pprof 性能分析工具

golang pprof 性能分析工具

訪問 som 性能分析工具 tar func mem rom 分享 場景

性能優化是個永恒的話題,而很多時候我們在作性能優化的時候,往往基於代碼上面的直覺,把所有能想到的優化都優化了一遍,不錯過任何小的優化點,結果整個代碼的邏輯變得極其復雜,而性能上面並沒有太大的提升。事實上,性能問題往往集中在某些小點,有時候很小的改動就能有巨大的提升,所以問題的關鍵是是怎麽去找出這些優化點,幸運的是 golang 在設計的時候就考慮了這個問題,原生提供了性能分析的工具,可以很方便地幫我們找到性能瓶頸

pprof 簡介

golang 的性能分析庫在 runtime/pprof 裏,主要提供下面幾個接口

// 堆棧分析
func WriteHeapProfile(w io.Writer) error
// cpu分析
func StartCPUProfile(w io.Writer) error
func StopCPUProfile()

使用上面比較簡單,只需要將文件指針傳給對應的函數即可,性能數據將寫入到文件中,然後可以使用 golang 自帶的 pprof 工具生成 svg,pdf 的可視化圖,然後就可以很直觀地從這些圖裏面看到主要的性能消耗了

舉個例子

首先需要一個程序

首先需要在你的程序裏面註入 pprof 代碼,下面是一段示例代碼,完整代碼在:https://github.com/hatlonely/hellogolang/blob/master/cmd/pprof_runtime.go,這裏使用的 PPCmd 方法,是為了方便使用,做的一個簡單封裝,代碼在:https://github.com/hatlonely/easygolang/blob/master/pprof/pprof.go

func main() {
    go doSomething1()
    go doSomething2()
    go doSomething3()

    if err := pprof.PPCmd("cpu 10s"); err != nil {
        panic(err)
    }

    if err := pprof.PPCmd("mem"); err != nil {
        panic(err)
    }
}

編譯,運行上面代碼會生成兩個 pprof 文件,cpu.pprof.yyyymmddhhmmssmem.pprof.yyyymmddhhmmss

,編譯運行的方法如下:

cd $GOPATH/src
git clone [email protected]:hatlonely/hellogolang.git
cd hellogolang
glide install
go build cmd/pprof_runtime.go
./pprof_runtime

pprof 文件分析

pprof 文件是二進制的,不是給人讀的,需要翻譯一下,而 golang 原生就給我們提供了分析工具,直接執行下面命令即可,會生成一張很直觀的 svg 圖片,直接用 chrome 就可以打開,當然也可以生成別的格式(pdf,png 都可以),可以用 go tool pprof -h 命令查看支持的輸出類型

go tool pprof -svg ./pprof_runtime cpu.pprof.201801301415 > cpu.svg

註意這個工具依賴於 graphviz 工具,Mac 上可用 brew install graphviz,centos yum install graphviz 即可

技術分享圖片

http 接口

net/http/pprof 裏面對 runtime/pprof 作了一些封裝,對外提供了 http 接口,可以直接通過瀏覽器訪問,但是只是一些字符串的結果,沒有作可視化,體驗並不是很好,用 go tool 訪問體驗能好一點

go tool pprof http://localhost:3000/debug/pprof/profile
go tool pprof http://localhost:3000/debug/pprof/heap

個人感覺這個接口比較雞肋,首先最大的問題是展示上面並不直觀,要是能直接在網頁上面可視化地展示可能還真的挺方便的;還有就是需要額外的提供一個 http 的端口,而這個接口還依賴 net/http這就意味著如果你的應用使用的是其他第三方的 http 庫,可能還需要解決兼容性的問題;實際上,我再使用這個接口的時候,在服務器壓力較大的場景下,會出現訪問超時,而這種壓力較大情況下的性能可能才是真正的性能瓶頸。

建議在根據的需求,自己封裝 runtime/pprof 的接口,當然是用場景比較簡單也可以用我上面的封裝,然後在服務裏面自己提供一個專門的性能分析接口(可能是 gprc,thrift,或者其他的第三方 http 框架)

火焰圖

除了上面生成的 svg 圖,還可以生成火焰圖,這是 uber 提供的一個工具,在顯示上面可能更直觀一些

安裝命令如下:

go get github.com/uber/go-torch
git clone [email protected]:brendangregg/FlameGraph.git
export PATH=$PATH:/path/to/FlameGraph

使用方法如下:

go-torch --binaryname=./pprof_runtime --binaryinput=cpu.pprof.201801301415

技術分享圖片

參考鏈接

  • Package pprof: https://golang.org/pkg/runtime/pprof/
  • Profiling Go Programs: https://blog.golang.org/profiling-go-programs
  • Go torch: https://github.com/uber/go-torch

轉載請註明出處
本文鏈接:http://hatlonely.github.io/2018/01/29/golang-pprof-性能分析工具/

golang pprof 性能分析工具