runtime/pprof

最後更新


runtime/pprof 套件在程式執行時收集效能剖析資料(profile),寫成 go tool pprof 能讀取的格式,用來找出 CPU 時間與記憶體花在哪裡。

這個套件做什麼


程式變慢或吃太多記憶體時,靠猜通常猜錯。剖析(profiling)的做法是讓 runtime 在執行期間定時取樣:每隔一小段時間記下「現在正在執行哪個函式」或「這塊記憶體是誰配置的」,最後統計出熱點。
runtime/pprof 負責收集並寫出資料,分析則交給 go tool pprof:
  1. go tool pprof -top cpu.prof
  2. go tool pprof -http=:8080 cpu.prof

前者在終端機列出最耗時的函式,後者開啟網頁介面,可以看火焰圖(flame graph)。完整流程與解讀方式見 pprof 效能剖析。
三種取得剖析資料的方式,依情境選擇:
情境做法
命令列工具、批次程式本頁的 runtime/pprof,寫入檔案
長時間執行的伺服器net/http/pprof,透過 HTTP 隨時抓取
測試與基準測試go test -cpuprofile cpu.prof -memprofile mem.prof,不用改程式碼

剖析資料的內容(函式耗時、配置量)每次執行都不同,所以本頁範例只印出檔案是否成功產生、數量等不受影響的結果。

匯入


  1. import "runtime/pprof"

常用 API


StartCPUProfile 與 StopCPUProfile


StartCPUProfile(w) 開始 CPU 剖析,取樣結果持續寫入 w;StopCPUProfile() 停止並把剩餘資料寫完。預設每秒取樣約 100 次,所以要剖析的程式至少要跑一段時間,資料才有意義。
慣用寫法是在 main 開頭啟動、緊接著 defer pprof.StopCPUProfile()。
注意:同一時間只能有一個 CPU 剖析在進行,已經啟動時再呼叫 StartCPUProfile 會回傳錯誤。
簽名:
  1. func StartCPUProfile(w io.Writer) error
  2. func StopCPUProfile()

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "runtime/pprof"
  7. "time"
  8. )
  9. func busy(d time.Duration) int {
  10. n := 0
  11. for start := time.Now(); time.Since(start) < d; {
  12. n++
  13. }
  14. return n
  15. }
  16. func main() {
  17. dir, err := os.MkdirTemp("", "pprof")
  18. if err != nil {
  19. fmt.Println(err)
  20. return
  21. }
  22. defer os.RemoveAll(dir)
  23. f, err := os.Create(filepath.Join(dir, "cpu.prof"))
  24. if err != nil {
  25. fmt.Println(err)
  26. return
  27. }
  28. defer f.Close()
  29. if err := pprof.StartCPUProfile(f); err != nil {
  30. fmt.Println(err)
  31. return
  32. }
  33. fmt.Println("第二次啟動:", pprof.StartCPUProfile(f))
  34. busy(300 * time.Millisecond)
  35. pprof.StopCPUProfile()
  36. info, _ := f.Stat()
  37. fmt.Println("cpu.prof 有內容:", info.Size() > 0)
  38. }

輸出:
  1. 第二次啟動: cpu profiling already in use
  2. cpu.prof 有內容: true

實際使用時把檔案寫在固定位置,再執行 go tool pprof -top cpu.prof 分析。

WriteHeapProfile


寫出堆積(heap)剖析:目前仍存活的記憶體是在哪些地方配置的,用來找記憶體洩漏或用量過大的原因。等同 Lookup("heap").WriteTo(w, 0)。
堆積剖析反映的是「上一次 GC 完成時」的狀態,所以寫出前先呼叫 runtime.GC(),資料會比較即時。
簽名:
  1. func WriteHeapProfile(w io.Writer) error

範例:
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "runtime"
  6. "runtime/pprof"
  7. )
  8. var cache [][]byte
  9. func fill() {
  10. for range 50 {
  11. cache = append(cache, make([]byte, 1<<20))
  12. }
  13. }
  14. func main() {
  15. fill()
  16. runtime.GC()
  17. var buf bytes.Buffer
  18. if err := pprof.WriteHeapProfile(&buf); err != nil {
  19. fmt.Println(err)
  20. return
  21. }
  22. fmt.Println("heap profile 有內容:", buf.Len() > 0)
  23. fmt.Printf("gzip 標頭: %x\n", buf.Bytes()[:2])
  24. }

輸出:
  1. heap profile 有內容: true
  2. gzip 標頭: 1f8b

預設格式是 gzip 壓縮的 protocol buffer,開頭兩個位元組固定是 1f8b。分析時用 go tool pprof -sample_index=inuse_space heap.prof 看目前占用量最大的地方。

Lookup 與 Profile.WriteTo


Lookup(name) 取得內建的剖析,名稱不存在時回傳 nil。常用的內建剖析:
名稱內容
goroutine所有 goroutine 目前的堆疊
heap存活物件的配置位置
allocs啟動以來所有配置的取樣
threadcreate建立作業系統執行緒的位置
block在同步原語上阻塞的位置(需先 runtime.SetBlockProfileRate)
mutex鎖競爭的位置(需先 runtime.SetMutexProfileFraction)

WriteTo(w, debug) 寫出剖析:debug 為 0 是給 go tool pprof 的二進位格式,1 是人看得懂的文字格式;goroutine 剖析的 debug=2 會印出跟 panic 時一樣的完整堆疊,排查卡住的 goroutine 很好用。Count() 回傳目前的項目數。
簽名:
  1. func Lookup(name string) *Profile
  2. func (p *Profile) WriteTo(w io.Writer, debug int) error
  3. func (p *Profile) Count() int

範例:
  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "runtime/pprof"
  6. "strings"
  7. "sync"
  8. )
  9. func main() {
  10. stop := make(chan struct{})
  11. var wg sync.WaitGroup
  12. for range 4 {
  13. wg.Go(func() { <-stop })
  14. }
  15. p := pprof.Lookup("goroutine")
  16. fmt.Println("goroutine 數:", p.Count())
  17. var buf bytes.Buffer
  18. p.WriteTo(&buf, 1)
  19. first := strings.SplitN(buf.String(), "\n", 2)[0]
  20. fmt.Println(first)
  21. fmt.Println(pprof.Lookup("no-such-profile") == nil)
  22. close(stop)
  23. wg.Wait()
  24. }

輸出:
  1. goroutine 數: 5
  2. goroutine profile: total 5
  3. true

debug=1 文字格式的第一行列出剖析名稱與總數,後面則是各堆疊與函式位置。

Profiles


回傳所有剖析(內建的加上用 NewProfile 自訂的),依名稱排序。可以用來列出目前可用的剖析種類。
簽名:
  1. func Profiles() []*Profile
  2. func (p *Profile) Name() string

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "runtime/pprof"
  5. )
  6. func main() {
  7. for _, p := range pprof.Profiles() {
  8. fmt.Println(p.Name())
  9. }
  10. }

輸出:
  1. allocs
  2. block
  3. goroutine
  4. heap
  5. mutex
  6. threadcreate

NewProfile 與 Profile.Add


NewProfile(name) 建立自訂剖析,用 Add(value, skip) 記下「某個物件在這裡被建立」(連同當下的堆疊),Remove(value) 移除。典型用途是追蹤尚未關閉的資源,例如連線或檔案:出現洩漏時,剖析會告訴你那些沒關的資源是在哪裡開的。
skip 是記錄堆疊時要略過的層數,0 表示從呼叫 Add 的函式開始記。名稱建議加上套件路徑前綴,避免和其他套件衝突。
注意:同名的剖析已存在時 NewProfile 會 panic;Add 同一個 value 兩次也會 panic。內建剖析不能呼叫 Add/Remove。
簽名:
  1. func NewProfile(name string) *Profile
  2. func (p *Profile) Add(value any, skip int)
  3. func (p *Profile) Remove(value any)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "runtime/pprof"
  5. )
  6. var openConns = pprof.NewProfile("example.com/demo.conns")
  7. type Conn struct{ id int }
  8. func Dial(id int) *Conn {
  9. c := &Conn{id: id}
  10. openConns.Add(c, 1)
  11. return c
  12. }
  13. func (c *Conn) Close() {
  14. openConns.Remove(c)
  15. }
  16. func main() {
  17. a := Dial(1)
  18. b := Dial(2)
  19. Dial(3)
  20. fmt.Println("開啟中:", openConns.Count())
  21. a.Close()
  22. b.Close()
  23. fmt.Println("關閉兩個後:", openConns.Count())
  24. fmt.Println("名稱:", openConns.Name())
  25. }

輸出:
  1. 開啟中: 3
  2. 關閉兩個後: 1
  3. 名稱: example.com/demo.conns

剩下的 1 個就是忘記關閉的 Dial(3)。這個剖析也會出現在 net/http/pprof 的頁面上,可以用 go tool pprof 查看它是在哪一行開啟的。

Do、Labels 與 Label


Do(ctx, labels, f) 在執行 f 期間替目前的 goroutine 貼上標籤(label),f 裡新開的 goroutine 也會繼承。CPU 與 goroutine 剖析會帶著這些標籤(其他剖析目前不使用標籤),之後可以用 go tool pprof -tagfocus=handler=login 只看某類請求的耗時。
  • Labels(k1, v1, k2, v2, ...):建立標籤組,參數必須成對,奇數個會 panic
  • Label(ctx, key):從 context 讀取標籤值
  • ForLabels(ctx, f):逐一走訪所有標籤

簽名:
  1. func Do(ctx context.Context, labels LabelSet, f func(context.Context))
  2. func Labels(args ...string) LabelSet
  3. func Label(ctx context.Context, key string) (string, bool)
  4. func ForLabels(ctx context.Context, f func(key, value string) bool)

範例:
  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "runtime/pprof"
  6. )
  7. func handle(ctx context.Context) {
  8. name, ok := pprof.Label(ctx, "handler")
  9. fmt.Println("handler:", name, ok)
  10. pprof.ForLabels(ctx, func(k, v string) bool {
  11. fmt.Printf(" %s=%s\n", k, v)
  12. return true
  13. })
  14. }
  15. func main() {
  16. ctx := context.Background()
  17. labels := pprof.Labels("handler", "login", "tenant", "acme")
  18. pprof.Do(ctx, labels, func(ctx context.Context) {
  19. handle(ctx)
  20. })
  21. _, ok := pprof.Label(ctx, "handler")
  22. fmt.Println("Do 外面讀得到:", ok)
  23. }

輸出:
  1. handler: login true
  2. handler=login
  3. tenant=acme
  4. Do 外面讀得到: false

重點整理


  • runtime/pprof 收集剖析資料,go tool pprof 負責分析與視覺化
  • CPU 剖析:StartCPUProfile 開始、defer StopCPUProfile() 結束,同時只能有一個
  • 堆積剖析:先 runtime.GC() 再 WriteHeapProfile
  • Lookup("goroutine").WriteTo(w, 2) 印出所有 goroutine 的堆疊,排查卡住或洩漏很實用
  • NewProfile 可自訂剖析追蹤未釋放的資源;Do 加標籤可依請求類型篩選剖析
  • 伺服器改用 net/http/pprof,測試直接用 go test -cpuprofile

資料來源