# pprof 效能剖析

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

## 什麼是效能剖析

程式跑得慢時，憑直覺猜「應該是這裡慢」常常猜錯。效能剖析（profiling）的做法是：讓程式一邊執行、一邊定期記錄「現在正在執行哪個函式」，最後統計出每個函式佔用了多少時間或記憶體。

像是在高速公路上每隔一段時間空拍一次，看哪一段最常塞車，就知道該先拓寬哪裡。

Go 內建這套工具，統稱 pprof：

| 工具 | 用途 |
| --- | --- |
| [`runtime/pprof`](/pkg-runtime-pprof) | 在程式中收集剖析資料並寫入檔案 |
| [`net/http/pprof`](/pkg-net-http-pprof) | 透過 HTTP 端點提供長時間執行服務的剖析資料 |
| `go test -cpuprofile` / `-memprofile` | 對測試或[基準測試](/testing-benchmark)直接剖析 |
| `go tool pprof` | 讀取剖析檔，以表格、原始碼或圖形呈現 |

常見的剖析種類：

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

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

## 收集與分析剖析資料

### CPU 剖析：runtime/pprof

在程式開頭呼叫 `pprof.StartCPUProfile` 開始記錄，結束前呼叫 `pprof.StopCPUProfile` 把資料寫完。適合執行一段時間就結束的命令列程式。

簽名：

```go
func StartCPUProfile(w io.Writer) error
func StopCPUProfile()
```

範例程式 `main.go`（`go.mod` 的 module 為 `example.com/prof`），用遞迴費氏數列與重複雜湊製造 CPU 負載：

```go
package main

import (
	"crypto/sha256"
	"fmt"
	"log"
	"os"
	"runtime/pprof"
)

func fib(n int) int {
	if n < 2 {
		return n
	}
	return fib(n-1) + fib(n-2)
}

func hashMany(n int) [32]byte {
	sum := sha256.Sum256([]byte("go"))
	for range n {
		sum = sha256.Sum256(sum[:])
	}
	return sum
}

func main() {
	f, err := os.Create("cpu.prof")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	if err := pprof.StartCPUProfile(f); err != nil {
		log.Fatal(err)
	}
	defer pprof.StopCPUProfile()

	fmt.Println("fib(42) =", fib(42))
	h := hashMany(20_000_000)
	fmt.Printf("hash = %x\n", h[:4])
}
```

執行：

```bash
go build -trimpath -o prof .
./prof
go tool pprof -top -nodecount=8 prof cpu.prof
```

輸出：

```text
fib(42) = 267914296
hash = 90964f45
File: prof
Type: cpu
Time: 2026-11-24 07:46:28 CST
Duration: 1.51s, Total samples = 1190ms (78.79%)
Showing nodes accounting for 1100ms, 92.44% of 1190ms total
Showing top 8 nodes out of 28
      flat  flat%   sum%        cum   cum%
     490ms 41.18% 41.18%      490ms 41.18%  main.fib
     350ms 29.41% 70.59%      350ms 29.41%  crypto/internal/fips140/sha256.blockSHA2
     100ms  8.40% 78.99%      510ms 42.86%  crypto/internal/fips140/sha256.(*Digest).Write
      50ms  4.20% 83.19%      480ms 40.34%  crypto/internal/fips140/sha256.(*Digest).checkSum
      40ms  3.36% 86.55%       40ms  3.36%  runtime.memmove
      30ms  2.52% 89.08%      510ms 42.86%  crypto/internal/fips140/sha256.(*Digest).Sum
      20ms  1.68% 90.76%       30ms  2.52%  crypto/internal/fips140/sha256.New
      20ms  1.68% 92.44%      370ms 31.09%  crypto/internal/fips140/sha256.block
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 去掉這個前綴，在目前目錄找原始碼：

```bash
go tool pprof -trim_path=example.com/prof -list 'main.fib' prof cpu.prof
```

輸出：

```text
Total: 1.19s
ROUTINE ======================== main.fib in main.go
     490ms      920ms (flat, cum) 77.31% of Total
     350ms      350ms     11:func fib(n int) int {
         .          .     12:	if n < 2 {
      80ms       80ms     13:		return n
         .          .     14:	}
      60ms      490ms     15:	return fib(n-1) + fib(n-2)
         .          .     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()`，讓「目前還活著的記憶體」統計是最新的。

簽名：

```go
func Lookup(name string) *Profile
func (p *Profile) WriteTo(w io.Writer, debug int) error
```

範例程式 `main.go`（`go.mod` 的 module 為 `example.com/memprof`）：`keep` 配置後一直保留，`build` 配置後立刻丟棄：

```go
package main

import (
	"fmt"
	"log"
	"os"
	"runtime"
	"runtime/pprof"
	"strings"
)

var cache [][]byte

func keep(n int) {
	for range n {
		cache = append(cache, make([]byte, 64*1024))
	}
}

func build(n int) int {
	total := 0
	for i := range n {
		s := strings.Repeat("x", i%1000)
		total += len(s)
	}
	return total
}

func main() {
	keep(200)
	fmt.Println("built", build(200_000))

	f, err := os.Create("mem.prof")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	runtime.GC()
	if err := pprof.Lookup("allocs").WriteTo(f, 0); err != nil {
		log.Fatal(err)
	}
	fmt.Println("cached", len(cache), "blocks")
}
```

執行：

```bash
go build -trimpath -o memprof .
./memprof
go tool pprof -sample_index=inuse_space -top -nodecount=4 memprof mem.prof
go tool pprof -sample_index=alloc_space -top -nodecount=6 memprof mem.prof
```

輸出：

```text
built 99900000
cached 200 blocks
File: memprof
Type: inuse_space
Time: 2026-11-24 07:46:55 CST
Showing nodes accounting for 17365.37kB, 100% of 17365.37kB total
Showing top 4 nodes out of 19
      flat  flat%   sum%        cum   cum%
16339.99kB 94.10% 94.10% 16339.99kB 94.10%  main.keep (inline)
 1025.38kB  5.90%   100%  1025.38kB  5.90%  runtime.mallocgc
         0     0%   100% 16339.99kB 94.10%  main.main
         0     0%   100%      513kB  2.95%  runtime.allocm
File: memprof
Type: alloc_space
Time: 2026-11-24 07:46:55 CST
Showing nodes accounting for 119.03MB, 100% of 119.03MB total
Dropped 15 nodes (cum <= 0.60MB)
Showing top 6 nodes out of 9
      flat  flat%   sum%        cum   cum%
  102.07MB 85.75% 85.75%   102.07MB 85.75%  internal/bytealg.MakeNoZero
   15.96MB 13.41% 99.16%    15.96MB 13.41%  main.keep (inline)
       1MB  0.84%   100%        1MB  0.84%  runtime.mallocgc
         0     0%   100%   102.07MB 85.75%  main.build
         0     0%   100%   118.02MB 99.16%  main.main
         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](/perf-gc)。

### go test -cpuprofile 與 -memprofile

對基準測試剖析最方便：不必改程式，加旗標就會產生剖析檔。`go test` 會同時把測試執行檔（`<套件名>.test`）留在目錄中。

被測程式 `join.go`：

```go
package join

import "strings"

func Concat(words []string) string {
	s := ""
	for _, w := range words {
		s += w
	}
	return s
}

func Builder(words []string) string {
	var b strings.Builder
	for _, w := range words {
		b.WriteString(w)
	}
	return b.String()
}
```

測試檔 `join_test.go`：

```go
package join

import "testing"

func BenchmarkConcat(b *testing.B) {
	words := make([]string, 100)
	for i := range words {
		words[i] = "go"
	}
	for b.Loop() {
		Concat(words)
	}
}
```

執行（`go.mod` 的 module 為 `example.com/join`）：

```bash
go test -bench=. -benchmem -cpuprofile=cpu.prof -memprofile=mem.prof
ls
go tool pprof -sample_index=alloc_space -top -nodecount=5 mem.prof
```

輸出：

```text
goos: darwin
goarch: arm64
pkg: example.com/join
cpu: Apple M5
BenchmarkConcat-10    	  579126	      2125 ns/op	   10736 B/op	      99 allocs/op
PASS
ok  	example.com/join	1.643s
cpu.prof
go.mod
join.go
join.test
join_test.go
mem.prof
File: join.test
Type: alloc_space
Time: 2026-11-24 07:46:57 CST
Showing nodes accounting for 5.84GB, 99.92% of 5.84GB total
Dropped 29 nodes (cum <= 0.03GB)
      flat  flat%   sum%        cum   cum%
    5.84GB 99.92% 99.92%     5.84GB 99.92%  example.com/join.Concat (inline)
         0     0% 99.92%     5.84GB 99.92%  example.com/join.BenchmarkConcat
         0     0% 99.92%     5.84GB 99.92%  testing.(*B).run1.func1
         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`）：

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	_ "net/http/pprof"
	"strings"
)

func main() {
	srv := httptest.NewServer(http.DefaultServeMux)
	defer srv.Close()

	for _, path := range []string{"/debug/pprof/", "/debug/pprof/goroutine?debug=1", "/debug/pprof/heap"} {
		resp, err := http.Get(srv.URL + path)
		if err != nil {
			fmt.Println(err)
			return
		}
		body, _ := io.ReadAll(resp.Body)
		resp.Body.Close()
		fmt.Println(path, resp.StatusCode, resp.Header.Get("Content-Type"))
		if path == "/debug/pprof/" {
			for _, name := range []string{"allocs", "block", "goroutine", "heap", "mutex", "profile", "threadcreate", "trace"} {
				fmt.Println("  has", name, strings.Contains(string(body), "href='"+name))
			}
		}
	}
}
```

輸出：

```text
/debug/pprof/ 200 text/html; charset=utf-8
  has allocs true
  has block true
  has goroutine true
  has heap true
  has mutex true
  has profile true
  has threadcreate true
  has trace true
/debug/pprof/goroutine?debug=1 200 text/plain; charset=utf-8
/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 不停計算雜湊：

```go
package main

import (
	"crypto/sha256"
	"fmt"
	"log"
	"net/http"
	_ "net/http/pprof"
)

func busy() {
	sum := sha256.Sum256([]byte("go"))
	for {
		sum = sha256.Sum256(sum[:])
	}
}

func main() {
	go busy()
	fmt.Println("listening on localhost:6060")
	log.Fatal(http.ListenAndServe("localhost:6060", nil))
}
```

在一個終端機執行服務，另一個終端機取樣 3 秒：

```bash
go build -o liveprof . && ./liveprof
PPROF_TMPDIR=profiles go tool pprof -top -nodecount=5 'http://localhost:6060/debug/pprof/profile?seconds=3'
```

輸出：

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

第一行是服務的輸出，其餘是 `go tool pprof` 的輸出。抓到的剖析檔會另存一份，預設在家目錄的 `pprof/` 下，這裡用 `PPROF_TMPDIR` 改存到 `profiles/`；這個 `.pb.gz` 檔之後可以重複分析，也可以拿來做 [PGO](/perf-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` 含呼叫的函式

## 資料來源

- [gopl-zh/gopl-zh.github.com（《Go 語言聖經》中譯本，章節架構參考）](https://github.com/gopl-zh/gopl-zh.github.com)
- [The Go Programming Language Specification](https://go.dev/ref/spec)
- [Go 官方文件](https://go.dev/doc/)
- [Go 官方部落格](https://go.dev/blog/)
