撰寫好了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)
}()

能通過這個網址檢查程式的記憶體分配,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占用總時間的比例 |
火焰圖方式

呼叫關系圖

3.參考
-
- 火焰圖工具網站
-
- Golang性能測驗工具PProf應用詳解
-
- 深度解密go語言之pprof
-
- graphviz官網
-
- Go 大殺器之性能剖析 PProf
-
- qcachegrindwin下載地址
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/242919.html
標籤:區塊鏈
下一篇:拖拽
