網上已搜索golang pprof,資料很多,簡明高效的一個沒看到,這篇文章5步教你用會pprof獲取cpu和內存prof。node
golang自帶的prof包是runtime/pprof,這個是低級別的,須要你手動作一些設置等等周邊工做,不利於咱們快速上手,利用pprof幫助咱們解決實際的問題。這裏推薦davecheney封裝的pprof,它能夠1行代碼,讓你用上pprof,專心解決本身的代碼問題,下載:git
go get github.com/pkg/profile
pprof生成的prof文件時二進制的,須要把這個二進制的文件轉換爲咱們人類可讀的,graphviz能夠幫助咱們把二進制的prof文件轉換爲圖像。Mac安裝:github
brew install graphviz
其餘系統安裝參考這裏Graphviz Download。golang
只須要爲hi.go
增長這一行,defer profile.Start().Stop()
,程序運行時,默認就會記錄cpu數據:bash
package main import ( "fmt" "github.com/pkg/profile" ) func main() { defer profile.Start().Stop() sl := makeSlice() fmt.Printf("sum = %d\n", sumSlice(sl)) } func makeSlice() []int { sl := make([]int, 10000000) for idx := range sl { sl[idx] = idx } return sl } func sumSlice(sl []int) int { sum := 0 for _, x := range sl { sum += x } return sum }
編譯和執行hi.go
。svg
go build hi.go ./hi
應當看到相似的結果,它輸出了生成的cpu.pprof的路徑:函數
2018/11/07 19:47:21 profile: cpu profiling enabled, /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile046201825/cpu.pprof sum = 49999995000000 2018/11/07 19:47:21 profile: cpu profiling disabled, /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile046201825/cpu.pprof
可視化有多種方式,能夠轉換爲text、pdf、svg等等。text命令是ui
go tool pprof --text /path/to/yourbinary /var/path/to/cpu.pprof
結果是:spa
go tool pprof -text ./hi /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile046201825/cpu.pprof File: hi Type: cpu Time: Nov 7, 2018 at 7:47pm (CST) Duration: 202.18ms, Total samples = 50ms (24.73%) Showing nodes accounting for 50ms, 100% of 50ms total flat flat% sum% cum cum% 40ms 80.00% 80.00% 40ms 80.00% main.makeSlice /Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go 10ms 20.00% 100% 10ms 20.00% main.sumSlice /Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go 0 0% 100% 50ms 100% main.main /Users/shitaibin/go/src/github.com/shitaibin/awesome/hi.go 0 0% 100% 50ms 100% runtime.main /usr/local/go/src/runtime/proc.go
還有pdf這種效果更好:code
go tool pprof --pdf /path/to/yourbinary /var/path/to/cpu.pprof > cpu.pdf
例子:
go tool pprof -pdf ./hi /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile046201825/cpu.pprof > cpu.pdf
效果:
5步已經結束,你已經學會使用cpu pprof了嗎?
若是你掌握了cpu pprof,mem pprof垂手可得就能拿下,只須要改1行代碼:
defer profile.Start(profile.MemProfile).Stop()
效果:
go tool pprof -pdf ./hi /var/folders/5g/rz16gqtx3nsdfs7k8sb80jth0000gn/T/profile986580758/mem.pprof > mem.pdf
若是這篇文章對你有幫助,請點個贊/喜歡,讓我知道個人寫做是有價值的,感謝。