天天看點

golang-pprof性能分析工具1.安裝環境2.性能監控代碼3.CPU性能檢視3.引用

編寫好了golang服務之後,接着要開始關注服務的CPU,記憶體使用情況。golang提供了性能剖析工具,記錄一些自己搜集到的資訊,寫下一些實踐的情況。在golang中内置了pprof工具,專門來做golang語言的優化。

  • 1.安裝環境
  • 2.性能監控代碼
  • 3.CPU性能檢視
  • 3.引用

1.安裝環境

go get -u github.com/google/pprof
           

2.性能監控代碼

這段代碼将會開啟一個http的網站,對外提供監控通路的位址。

import (
	"net/http"
    _ "net/http/pprof"
)
go func() {
    http.ListenAndServe(":10003", nil)
}()
           
golang-pprof性能分析工具1.安裝環境2.性能監控代碼3.CPU性能檢視3.引用

能通過這個網址檢查程式的記憶體配置設定,CPU占用,mutex,gorouine之類的資訊。可以直接通過浏覽器通路擷取資訊。

  • CPU profile:報告程式的 CPU 使用情況,按照一定頻率去采集應用程式在 CPU 和寄存器上面的資料
  • Memory Profile(Heap Profile):報告程式的記憶體使用情況
  • Block Profiling:報告 goroutines 不在運作狀态的情況,可以用來分析和查找死鎖等性能瓶頸
  • Goroutine Profiling:報告 goroutines 的使用情況,有哪些 goroutine,它們的調用關系是怎樣的

3.CPU性能檢視

打開一個指令行輸入:

PS D:\work\trunk\doc> go tool pprof -http=":8081" http://127.0.0.1:10006/debug/pprof/profile?seconds=200
Fetching profile over HTTP from http://127.0.0.1:10006/debug/pprof/profile?seconds=200
Saved profile in C:\Users\xxxxxxxxx\pprof\pprof.samples.cpu.003.pb.gz
Serving web UI on http://localhost:8081
           

在本地将會開啟 -http=":8081" 表示在8081網站,将會呈現最後結果。這次監控将會抓取 http://127.0.0.1:10006/debug/pprof/profile 提供的性能資訊。?seconds=200 表示持續抓取200sec。到時間之後它們将會存儲到本地的一個檔案中: Saved profile in C:\Users\xxxxxxxxx\pprof\pprof.samples.cpu.003.pb.gz 。

想知道這個處理的細節,可以直接閱讀golang的源碼:

// C:\Go\src\net\http\pprof\pprof.go
// Profile responds with the pprof-formatted cpu profile.
// Profiling lasts for duration specified in seconds GET parameter, or for 30 seconds if not specified.
// The package initialization registers it as /debug/pprof/profile.
func Profile(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("X-Content-Type-Options", "nosniff")
	sec, err := strconv.ParseInt(r.FormValue("seconds"), 10, 64)
	if sec <= 0 || err != nil {
		sec = 30
	}
}
           

它的接口有兩個能支援輸入seconds

"trace":        "A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace.",
"profile":      "CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile.",
           

通過加載檔案來調出分析網站:

PS D:\work\trunk\doc> go tool pprof -http=":8989" C:\Users\xxxxxxxxx\pprof\pprof.samples.cpu.003.pb.gz
Serving web UI on http://localhost:8989
           

也能通過這個指令直接加載之前監控的剖析檔案。

列名 含義
flat 函數執行消耗時間,采樣時,該函數正在運作的次數*采樣頻率(10ms),即得到估算的函數運作”采樣時間”。這裡不包括函數等待子函數傳回。
flat% flat / 總采樣時間值
sum% 前面每一行的flat占比總和
cum 累計量,該函數出現在調用堆棧的采樣時間,包括函數等待子函數傳回。是以 flat <= cum
cum% cum占用總時間的比例

火焰圖方式

golang-pprof性能分析工具1.安裝環境2.性能監控代碼3.CPU性能檢視3.引用

調用關系圖

golang-pprof性能分析工具1.安裝環境2.性能監控代碼3.CPU性能檢視3.引用

3.引用

  • [1] 火焰圖工具網站
  • [2] Golang性能測試工具PProf應用詳解
  • [3] 深度解密go語言之pprof
  • [4] graphviz官網
  • [5] Go 大殺器之性能剖析 PProf
  • [6] qcachegrindwin下載下傳位址