golang-pprof性能分析工具

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

1.安裝環境

go get -u github.com/google/pprof

2.性能監控代碼

這段代碼將會開啓一個http的網站,對外提供監控訪問的地址。

import (
	"net/http"
    _ "net/http/pprof"
)
go func() {
   
   
    http.ListenAndServe(":10003", nil)
}()

rL0XUx.png

能通過這個網址檢查程序的內存分配,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佔用總時間的比例

火焰圖方式

rLfQUg.png

調用關係圖

rL0OV1.png

3.引用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章