pprof 效能剖析

最後更新


本頁說明如何用 pprof 收集 CPU 與記憶體剖析資料,並用 go tool pprof 找出程式中最耗時、最耗記憶體的地方。

什麼是效能剖析


程式跑得慢時,憑直覺猜「應該是這裡慢」常常猜錯。效能剖析(profiling)的做法是:讓程式一邊執行、一邊定期記錄「現在正在執行哪個函式」,最後統計出每個函式佔用了多少時間或記憶體。
像是在高速公路上每隔一段時間空拍一次,看哪一段最常塞車,就知道該先拓寬哪裡。
Go 內建這套工具,統稱 pprof:
工具用途
runtime/pprof在程式中收集剖析資料並寫入檔案
net/http/pprof透過 HTTP 端點提供長時間執行服務的剖析資料
go test -cpuprofile / -memprofile對測試或基準測試直接剖析
go tool pprof讀取剖析檔,以表格、原始碼或圖形呈現

常見的剖析種類:
種類回答的問題
CPU哪些函式最花 CPU 時間
heap目前還活著的物件佔用多少記憶體、在哪裡配置的
allocs程式開始以來總共配置了多少記憶體
goroutine目前所有 goroutine 停在哪裡

注意:剖析是「取樣」,CPU 預設每秒取樣 100 次,記憶體約每配置 512 KB 取樣一次。本頁所有耗時與記憶體數字都會因機器、Go 版本與每次執行而不同,請看比例而非絕對值。

收集與分析剖析資料


CPU 剖析:runtime/pprof


在程式開頭呼叫 pprof.StartCPUProfile 開始記錄,結束前呼叫 pprof.StopCPUProfile 把資料寫完。適合執行一段時間就結束的命令列程式。
簽名:
  1. func StartCPUProfile(w io.Writer) error
  2. func StopCPUProfile()

範例程式 main.go(go.mod 的 module 為 example.com/prof),用遞迴費氏數列與重複雜湊製造 CPU 負載:
  1. package main
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "log"
  6. "os"
  7. "runtime/pprof"
  8. )
  9. func fib(n int) int {
  10. if n < 2 {
  11. return n
  12. }
  13. return fib(n-1) + fib(n-2)
  14. }
  15. func hashMany(n int) [32]byte {
  16. sum := sha256.Sum256([]byte("go"))
  17. for range n {
  18. sum = sha256.Sum256(sum[:])
  19. }
  20. return sum
  21. }
  22. func main() {
  23. f, err := os.Create("cpu.prof")
  24. if err != nil {
  25. log.Fatal(err)
  26. }
  27. defer f.Close()
  28. if err := pprof.StartCPUProfile(f); err != nil {
  29. log.Fatal(err)
  30. }
  31. defer pprof.StopCPUProfile()
  32. fmt.Println("fib(42) =", fib(42))
  33. h := hashMany(20_000_000)
  34. fmt.Printf("hash = %x\n", h[:4])
  35. }

執行:
  1. go build -trimpath -o prof .
  2. ./prof
  3. go tool pprof -top -nodecount=8 prof cpu.prof

輸出:
  1. fib(42) = 267914296
  2. hash = 90964f45
  3. File: prof
  4. Type: cpu
  5. Time: 2026-11-24 07:46:28 CST
  6. Duration: 1.51s, Total samples = 1190ms (78.79%)
  7. Showing nodes accounting for 1100ms, 92.44% of 1190ms total
  8. Showing top 8 nodes out of 28
  9. flat flat% sum% cum cum%
  10. 490ms 41.18% 41.18% 490ms 41.18% main.fib
  11. 350ms 29.41% 70.59% 350ms 29.41% crypto/internal/fips140/sha256.blockSHA2
  12. 100ms 8.40% 78.99% 510ms 42.86% crypto/internal/fips140/sha256.(*Digest).Write
  13. 50ms 4.20% 83.19% 480ms 40.34% crypto/internal/fips140/sha256.(*Digest).checkSum
  14. 40ms 3.36% 86.55% 40ms 3.36% runtime.memmove
  15. 30ms 2.52% 89.08% 510ms 42.86% crypto/internal/fips140/sha256.(*Digest).Sum
  16. 20ms 1.68% 90.76% 30ms 2.52% crypto/internal/fips140/sha256.New
  17. 20ms 1.68% 92.44% 370ms 31.09% crypto/internal/fips140/sha256.block
  18. Total: 1.19s

-top 以表格列出最耗時的函式,-nodecount 限制列出幾行。兩個最重要的欄位:
欄位意義
flat函式自己執行的時間,不含它呼叫的其他函式
cum累計時間,包含它呼叫的所有函式

main.fib 的 flat 最高,代表時間花在它本身;sha256.(*Digest).Write 的 flat 不高但 cum 很高,代表時間花在它呼叫的 blockSHA2。耗時與百分比因機器而異。
-list <regexp> 會把指定函式的原始碼逐行標上耗時。go build -trimpath 讓執行檔記錄模組路徑(example.com/prof/main.go)而非本機絕對路徑,-trim_path 告訴 pprof 去掉這個前綴,在目前目錄找原始碼:
  1. go tool pprof -trim_path=example.com/prof -list 'main.fib' prof cpu.prof

輸出:
  1. Total: 1.19s
  2. ROUTINE ======================== main.fib in main.go
  3. 490ms 920ms (flat, cum) 77.31% of Total
  4. 350ms 350ms 11:func fib(n int) int {
  5. . . 12: if n < 2 {
  6. 80ms 80ms 13: return n
  7. . . 14: }
  8. 60ms 490ms 15: return fib(n-1) + fib(n-2)
  9. . . 16:}

不加 -top、-list 時,go tool pprof prof cpu.prof 會進入互動模式,可以輸入 top、list fib、web(以瀏覽器顯示呼叫圖,需安裝 Graphviz)等指令,輸入 quit 離開。

記憶體剖析:heap 與 allocs


記憶體剖析不必開始與結束,在想觀察的時間點把剖析資料寫出即可。pprof.Lookup("allocs") 與 pprof.Lookup("heap") 內容相同,只是 go tool pprof 預設顯示的指標不同。寫出前先呼叫 runtime.GC(),讓「目前還活著的記憶體」統計是最新的。
簽名:
  1. func Lookup(name string) *Profile
  2. func (p *Profile) WriteTo(w io.Writer, debug int) error

範例程式 main.go(go.mod 的 module 為 example.com/memprof):keep 配置後一直保留,build 配置後立刻丟棄:
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "runtime"
  7. "runtime/pprof"
  8. "strings"
  9. )
  10. var cache [][]byte
  11. func keep(n int) {
  12. for range n {
  13. cache = append(cache, make([]byte, 64*1024))
  14. }
  15. }
  16. func build(n int) int {
  17. total := 0
  18. for i := range n {
  19. s := strings.Repeat("x", i%1000)
  20. total += len(s)
  21. }
  22. return total
  23. }
  24. func main() {
  25. keep(200)
  26. fmt.Println("built", build(200_000))
  27. f, err := os.Create("mem.prof")
  28. if err != nil {
  29. log.Fatal(err)
  30. }
  31. defer f.Close()
  32. runtime.GC()
  33. if err := pprof.Lookup("allocs").WriteTo(f, 0); err != nil {
  34. log.Fatal(err)
  35. }
  36. fmt.Println("cached", len(cache), "blocks")
  37. }

執行:
  1. go build -trimpath -o memprof .
  2. ./memprof
  3. go tool pprof -sample_index=inuse_space -top -nodecount=4 memprof mem.prof
  4. go tool pprof -sample_index=alloc_space -top -nodecount=6 memprof mem.prof

輸出:
  1. built 99900000
  2. cached 200 blocks
  3. File: memprof
  4. Type: inuse_space
  5. Time: 2026-11-24 07:46:55 CST
  6. Showing nodes accounting for 17365.37kB, 100% of 17365.37kB total
  7. Showing top 4 nodes out of 19
  8. flat flat% sum% cum cum%
  9. 16339.99kB 94.10% 94.10% 16339.99kB 94.10% main.keep (inline)
  10. 1025.38kB 5.90% 100% 1025.38kB 5.90% runtime.mallocgc
  11. 0 0% 100% 16339.99kB 94.10% main.main
  12. 0 0% 100% 513kB 2.95% runtime.allocm
  13. File: memprof
  14. Type: alloc_space
  15. Time: 2026-11-24 07:46:55 CST
  16. Showing nodes accounting for 119.03MB, 100% of 119.03MB total
  17. Dropped 15 nodes (cum <= 0.60MB)
  18. Showing top 6 nodes out of 9
  19. flat flat% sum% cum cum%
  20. 102.07MB 85.75% 85.75% 102.07MB 85.75% internal/bytealg.MakeNoZero
  21. 15.96MB 13.41% 99.16% 15.96MB 13.41% main.keep (inline)
  22. 1MB 0.84% 100% 1MB 0.84% runtime.mallocgc
  23. 0 0% 100% 102.07MB 85.75% main.build
  24. 0 0% 100% 118.02MB 99.16% main.main
  25. 0 0% 100% 118.02MB 99.16% runtime.main

-sample_index 選擇要看的指標:
指標意義用來找
inuse_space目前還活著的位元組數記憶體洩漏、常駐記憶體太大
alloc_space累計配置的位元組數配置太頻繁、造成 GC 壓力的地方
inuse_objects / alloc_objects同上,但以物件個數計大量小物件

inuse_space 顯示 keep 佔了大部分常駐記憶體(約 16 MB 的快取);alloc_space 則顯示 build 透過 strings.Repeat 累計配置了約 100 MB,雖然都已被 GC 回收。數字因機器與每次執行而異。減少配置的方法見記憶體與 GC。

go test -cpuprofile 與 -memprofile


對基準測試剖析最方便:不必改程式,加旗標就會產生剖析檔。go test 會同時把測試執行檔(<套件名>.test)留在目錄中。
被測程式 join.go:
  1. package join
  2. import "strings"
  3. func Concat(words []string) string {
  4. s := ""
  5. for _, w := range words {
  6. s += w
  7. }
  8. return s
  9. }
  10. func Builder(words []string) string {
  11. var b strings.Builder
  12. for _, w := range words {
  13. b.WriteString(w)
  14. }
  15. return b.String()
  16. }

測試檔 join_test.go:
  1. package join
  2. import "testing"
  3. func BenchmarkConcat(b *testing.B) {
  4. words := make([]string, 100)
  5. for i := range words {
  6. words[i] = "go"
  7. }
  8. for b.Loop() {
  9. Concat(words)
  10. }
  11. }

執行(go.mod 的 module 為 example.com/join):
  1. go test -bench=. -benchmem -cpuprofile=cpu.prof -memprofile=mem.prof
  2. ls
  3. go tool pprof -sample_index=alloc_space -top -nodecount=5 mem.prof

輸出:
  1. goos: darwin
  2. goarch: arm64
  3. pkg: example.com/join
  4. cpu: Apple M5
  5. BenchmarkConcat-10 579126 2125 ns/op 10736 B/op 99 allocs/op
  6. PASS
  7. ok example.com/join 1.643s
  8. cpu.prof
  9. go.mod
  10. join.go
  11. join.test
  12. join_test.go
  13. mem.prof
  14. File: join.test
  15. Type: alloc_space
  16. Time: 2026-11-24 07:46:57 CST
  17. Showing nodes accounting for 5.84GB, 99.92% of 5.84GB total
  18. Dropped 29 nodes (cum <= 0.03GB)
  19. flat flat% sum% cum cum%
  20. 5.84GB 99.92% 99.92% 5.84GB 99.92% example.com/join.Concat (inline)
  21. 0 0% 99.92% 5.84GB 99.92% example.com/join.BenchmarkConcat
  22. 0 0% 99.92% 5.84GB 99.92% testing.(*B).run1.func1
  23. 0 0% 99.92% 5.84GB 99.92% testing.(*B).runN

基準測試跑了約 58 萬次,累計配置將近 6 GB,幾乎全來自 Concat。cpu.prof 也用同樣的 go tool pprof -top cpu.prof 分析。耗時、次數與累計量都因機器而異。
注意:剖析旗標一次只能用在一個套件,不能搭配 ./...。

net/http/pprof:剖析執行中的服務


伺服器這類長時間執行的程式,適合用 net/http/pprof。只要用空白識別字匯入(import _ "net/http/pprof"),它就會在 http.DefaultServeMux 上註冊 /debug/pprof/ 底下的端點。
下面的範例用 httptest 起本機伺服器,確認這些端點都存在(go.mod 的 module 為 example.com/webprof):
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. _ "net/http/pprof"
  8. "strings"
  9. )
  10. func main() {
  11. srv := httptest.NewServer(http.DefaultServeMux)
  12. defer srv.Close()
  13. for _, path := range []string{"/debug/pprof/", "/debug/pprof/goroutine?debug=1", "/debug/pprof/heap"} {
  14. resp, err := http.Get(srv.URL + path)
  15. if err != nil {
  16. fmt.Println(err)
  17. return
  18. }
  19. body, _ := io.ReadAll(resp.Body)
  20. resp.Body.Close()
  21. fmt.Println(path, resp.StatusCode, resp.Header.Get("Content-Type"))
  22. if path == "/debug/pprof/" {
  23. for _, name := range []string{"allocs", "block", "goroutine", "heap", "mutex", "profile", "threadcreate", "trace"} {
  24. fmt.Println(" has", name, strings.Contains(string(body), "href='"+name))
  25. }
  26. }
  27. }
  28. }

輸出:
  1. /debug/pprof/ 200 text/html; charset=utf-8
  2. has allocs true
  3. has block true
  4. has goroutine true
  5. has heap true
  6. has mutex true
  7. has profile true
  8. has threadcreate true
  9. has trace true
  10. /debug/pprof/goroutine?debug=1 200 text/plain; charset=utf-8
  11. /debug/pprof/heap 200 application/octet-stream

/debug/pprof/ 是索引頁;加 ?debug=1 回傳人看得懂的文字,不加則回傳給 go tool pprof 讀的二進位格式。profile 是 CPU 剖析,用 ?seconds=N 指定取樣秒數。
實際使用時,讓服務在本機連接埠上執行,再用 go tool pprof 直接連線取樣。範例程式 main.go(go.mod 的 module 為 example.com/liveprof),背景 goroutine 不停計算雜湊:
  1. package main
  2. import (
  3. "crypto/sha256"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. _ "net/http/pprof"
  8. )
  9. func busy() {
  10. sum := sha256.Sum256([]byte("go"))
  11. for {
  12. sum = sha256.Sum256(sum[:])
  13. }
  14. }
  15. func main() {
  16. go busy()
  17. fmt.Println("listening on localhost:6060")
  18. log.Fatal(http.ListenAndServe("localhost:6060", nil))
  19. }

在一個終端機執行服務,另一個終端機取樣 3 秒:
  1. go build -o liveprof . && ./liveprof
  2. PPROF_TMPDIR=profiles go tool pprof -top -nodecount=5 'http://localhost:6060/debug/pprof/profile?seconds=3'

輸出:
  1. listening on localhost:6060
  2. Fetching profile over HTTP from http://localhost:6060/debug/pprof/profile?seconds=3
  3. Saved profile in profiles/pprof.liveprof.samples.cpu.001.pb.gz
  4. File: liveprof
  5. Type: cpu
  6. Time: 2026-11-24 07:47:39 CST
  7. Duration: 3.13s, Total samples = 2690ms (86.01%)
  8. Showing nodes accounting for 2240ms, 83.27% of 2690ms total
  9. Showing top 5 nodes out of 23
  10. flat flat% sum% cum cum%
  11. 1190ms 44.24% 44.24% 1190ms 44.24% crypto/internal/fips140/sha256.blockSHA2
  12. 470ms 17.47% 61.71% 1870ms 69.52% crypto/internal/fips140/sha256.(*Digest).Write
  13. 280ms 10.41% 72.12% 1980ms 73.61% crypto/internal/fips140/sha256.(*Digest).checkSum
  14. 180ms 6.69% 78.81% 2210ms 82.16% crypto/internal/fips140/sha256.(*Digest).Sum
  15. 120ms 4.46% 83.27% 120ms 4.46% runtime.memmove

第一行是服務的輸出,其餘是 go tool pprof 的輸出。抓到的剖析檔會另存一份,預設在家目錄的 pprof/ 下,這裡用 PPROF_TMPDIR 改存到 profiles/;這個 .pb.gz 檔之後可以重複分析,也可以拿來做 PGO。耗時數字因機器而異。
注意:/debug/pprof/ 會暴露程式內部資訊,也能讓人觸發耗 CPU 的取樣。正式環境只讓它監聽 localhost 或內部網路,不要掛在對外公開的連接埠上。block 與 mutex 剖析預設不收集資料,需要先呼叫 runtime.SetBlockProfileRate 與 runtime.SetMutexProfileFraction 開啟。

重點整理


  • pprof 以取樣統計每個函式的 CPU 時間與記憶體配置,數字因機器而異,看比例
  • 命令列程式用 runtime/pprof:CPU 用 StartCPUProfile/StopCPUProfile,記憶體用 Lookup("heap") 或 Lookup("allocs") 寫出
  • 基準測試直接加 -cpuprofile、-memprofile 旗標
  • 長時間執行的服務匯入 _ "net/http/pprof",再用 go tool pprof <URL> 取樣,端點不要對外公開
  • go tool pprof -top 看排行、-list 看逐行耗時;flat 是自身時間、cum 含呼叫的函式

資料來源