# runtime/pprof

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

## 這個套件做什麼

程式變慢或吃太多記憶體時，靠猜通常猜錯。剖析（profiling）的做法是讓 runtime 在執行期間定時取樣：每隔一小段時間記下「現在正在執行哪個函式」或「這塊記憶體是誰配置的」，最後統計出熱點。

`runtime/pprof` 負責收集並寫出資料，分析則交給 `go tool pprof`：

```bash
go tool pprof -top cpu.prof
go tool pprof -http=:8080 cpu.prof
```

前者在終端機列出最耗時的函式，後者開啟網頁介面，可以看火焰圖（flame graph）。完整流程與解讀方式見 [pprof 效能剖析](/perf-pprof)。

三種取得剖析資料的方式，依情境選擇：

| 情境 | 做法 |
| --- | --- |
| 命令列工具、批次程式 | 本頁的 `runtime/pprof`，寫入檔案 |
| 長時間執行的伺服器 | [`net/http/pprof`](/pkg-net-http-pprof)，透過 HTTP 隨時抓取 |
| 測試與基準測試 | `go test -cpuprofile cpu.prof -memprofile mem.prof`，不用改程式碼 |

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

## 匯入

```go
import "runtime/pprof"
```

## 常用 API

### StartCPUProfile 與 StopCPUProfile

`StartCPUProfile(w)` 開始 CPU 剖析，取樣結果持續寫入 `w`；`StopCPUProfile()` 停止並把剩餘資料寫完。預設每秒取樣約 100 次，所以要剖析的程式至少要跑一段時間，資料才有意義。

慣用寫法是在 `main` 開頭啟動、緊接著 `defer pprof.StopCPUProfile()`。

注意：同一時間只能有一個 CPU 剖析在進行，已經啟動時再呼叫 `StartCPUProfile` 會回傳錯誤。

簽名：

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

範例：

```go
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime/pprof"
	"time"
)

func busy(d time.Duration) int {
	n := 0
	for start := time.Now(); time.Since(start) < d; {
		n++
	}
	return n
}

func main() {
	dir, err := os.MkdirTemp("", "pprof")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(dir)

	f, err := os.Create(filepath.Join(dir, "cpu.prof"))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer f.Close()

	if err := pprof.StartCPUProfile(f); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("第二次啟動:", pprof.StartCPUProfile(f))

	busy(300 * time.Millisecond)
	pprof.StopCPUProfile()

	info, _ := f.Stat()
	fmt.Println("cpu.prof 有內容:", info.Size() > 0)
}
```

輸出：

```text
第二次啟動: cpu profiling already in use
cpu.prof 有內容: true
```

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

### WriteHeapProfile

寫出堆積（heap）剖析：目前仍存活的記憶體是在哪些地方配置的，用來找記憶體洩漏或用量過大的原因。等同 `Lookup("heap").WriteTo(w, 0)`。

堆積剖析反映的是「上一次 GC 完成時」的狀態，所以寫出前先呼叫 `runtime.GC()`，資料會比較即時。

簽名：

```go
func WriteHeapProfile(w io.Writer) error
```

範例：

```go
package main

import (
	"bytes"
	"fmt"
	"runtime"
	"runtime/pprof"
)

var cache [][]byte

func fill() {
	for range 50 {
		cache = append(cache, make([]byte, 1<<20))
	}
}

func main() {
	fill()
	runtime.GC()

	var buf bytes.Buffer
	if err := pprof.WriteHeapProfile(&buf); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("heap profile 有內容:", buf.Len() > 0)
	fmt.Printf("gzip 標頭: %x\n", buf.Bytes()[:2])
}
```

輸出：

```text
heap profile 有內容: true
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()` 回傳目前的項目數。

簽名：

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

範例：

```go
package main

import (
	"bytes"
	"fmt"
	"runtime/pprof"
	"strings"
	"sync"
)

func main() {
	stop := make(chan struct{})
	var wg sync.WaitGroup
	for range 4 {
		wg.Go(func() { <-stop })
	}

	p := pprof.Lookup("goroutine")
	fmt.Println("goroutine 數:", p.Count())

	var buf bytes.Buffer
	p.WriteTo(&buf, 1)
	first := strings.SplitN(buf.String(), "\n", 2)[0]
	fmt.Println(first)

	fmt.Println(pprof.Lookup("no-such-profile") == nil)

	close(stop)
	wg.Wait()
}
```

輸出：

```text
goroutine 數: 5
goroutine profile: total 5
true
```

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

### Profiles

回傳所有剖析（內建的加上用 `NewProfile` 自訂的），依名稱排序。可以用來列出目前可用的剖析種類。

簽名：

```go
func Profiles() []*Profile
func (p *Profile) Name() string
```

範例：

```go
package main

import (
	"fmt"
	"runtime/pprof"
)

func main() {
	for _, p := range pprof.Profiles() {
		fmt.Println(p.Name())
	}
}
```

輸出：

```text
allocs
block
goroutine
heap
mutex
threadcreate
```

### NewProfile 與 Profile.Add

`NewProfile(name)` 建立自訂剖析，用 `Add(value, skip)` 記下「某個物件在這裡被建立」（連同當下的堆疊），`Remove(value)` 移除。典型用途是追蹤尚未關閉的資源，例如連線或檔案：出現洩漏時，剖析會告訴你那些沒關的資源是在哪裡開的。

`skip` 是記錄堆疊時要略過的層數，0 表示從呼叫 `Add` 的函式開始記。名稱建議加上套件路徑前綴，避免和其他套件衝突。

注意：同名的剖析已存在時 `NewProfile` 會 panic；`Add` 同一個 `value` 兩次也會 panic。內建剖析不能呼叫 `Add`／`Remove`。

簽名：

```go
func NewProfile(name string) *Profile
func (p *Profile) Add(value any, skip int)
func (p *Profile) Remove(value any)
```

範例：

```go
package main

import (
	"fmt"
	"runtime/pprof"
)

var openConns = pprof.NewProfile("example.com/demo.conns")

type Conn struct{ id int }

func Dial(id int) *Conn {
	c := &Conn{id: id}
	openConns.Add(c, 1)
	return c
}

func (c *Conn) Close() {
	openConns.Remove(c)
}

func main() {
	a := Dial(1)
	b := Dial(2)
	Dial(3)
	fmt.Println("開啟中:", openConns.Count())

	a.Close()
	b.Close()
	fmt.Println("關閉兩個後:", openConns.Count())
	fmt.Println("名稱:", openConns.Name())
}
```

輸出：

```text
開啟中: 3
關閉兩個後: 1
名稱: 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)`：逐一走訪所有標籤

簽名：

```go
func Do(ctx context.Context, labels LabelSet, f func(context.Context))
func Labels(args ...string) LabelSet
func Label(ctx context.Context, key string) (string, bool)
func ForLabels(ctx context.Context, f func(key, value string) bool)
```

範例：

```go
package main

import (
	"context"
	"fmt"
	"runtime/pprof"
)

func handle(ctx context.Context) {
	name, ok := pprof.Label(ctx, "handler")
	fmt.Println("handler:", name, ok)

	pprof.ForLabels(ctx, func(k, v string) bool {
		fmt.Printf("  %s=%s\n", k, v)
		return true
	})
}

func main() {
	ctx := context.Background()
	labels := pprof.Labels("handler", "login", "tenant", "acme")
	pprof.Do(ctx, labels, func(ctx context.Context) {
		handle(ctx)
	})

	_, ok := pprof.Label(ctx, "handler")
	fmt.Println("Do 外面讀得到:", ok)
}
```

輸出：

```text
handler: login true
  handler=login
  tenant=acme
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`

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：runtime/pprof](https://pkg.go.dev/runtime/pprof)
- [Go 1.26.0 原始碼：src/runtime/pprof](https://github.com/golang/go/tree/go1.26.0/src/runtime/pprof)
