runtime/debug
最後更新
runtime/debug 套件提供程式在執行中「自我檢查與調整」的工具:取得堆疊追蹤、讀取建置資訊、調整垃圾回收與記憶體上限。這個套件做什麼
runtime 處理日常的執行環境查詢,runtime/debug 則收錄比較偏維運與除錯的功能:| 想做的事 | API |
|---|---|
| recover 之後把堆疊記進 log | Stack、PrintStack |
| 印出版本號、commit、依賴模組 | ReadBuildInfo |
調整 GC 頻率(等同 GOGC 環境變數) | SetGCPercent |
設定記憶體軟上限(等同 GOMEMLIMIT) | SetMemoryLimit |
| 立刻把空閒記憶體還給作業系統 | FreeOSMemory |
| 讀取 GC 次數與暫停時間 | ReadGCStats |
GC 的運作與
GOGC、GOMEMLIMIT 的觀念見 記憶體與 GC;效能剖析請用 runtime/pprof。注意:部分輸出依機器與建置方式而異,本頁範例是在本機 go1.26.0、darwin/arm64,以
go build 建置後執行的結果。匯入
- import "runtime/debug"
常用 API
Stack 與 PrintStack
Stack():回傳呼叫它的 goroutine 目前的堆疊追蹤(stack trace),格式與 panic 時印出的相同PrintStack():直接把同樣的內容印到標準錯誤輸出(stderr)
最常見的用途是在
recover 之後記錄堆疊,這樣程式不會崩潰,事後也查得到是哪裡出錯(觀念見 panic 與 recover)。堆疊內容包含原始檔的完整路徑與記憶體偏移量,每台機器都不同,範例只挑出函式名稱那幾行。
簽名:
- func Stack() []byte
- func PrintStack()
範例:
- package main
- import (
- "fmt"
- "runtime/debug"
- "strings"
- )
- func safeRun(f func()) {
- defer func() {
- if r := recover(); r != nil {
- fmt.Println("recovered:", r)
- for _, line := range strings.Split(string(debug.Stack()), "\n") {
- if strings.HasPrefix(line, "main.") || strings.HasPrefix(line, "goroutine ") {
- fmt.Println(" ", line[:strings.IndexAny(line, "(:")])
- }
- }
- }
- }()
- f()
- }
- func divide(a, b int) int {
- return a / b
- }
- func main() {
- safeRun(func() {
- fmt.Println(divide(10, 0))
- })
- fmt.Println("程式繼續執行")
- }
輸出:
- recovered: runtime error: integer divide by zero
- goroutine 1 [running]
- main.safeRun.func1
- main.divide
- main.main.func1
- main.safeRun
- main.main
- 程式繼續執行
堆疊由內往外列出。篩選掉 runtime 內部函式後,最上面是
recover 所在的延遲函式,往下依序是發生 panic 的 divide、匿名函式、safeRun、main。main.main.func1 是 main 裡面第一個匿名函式的名稱。ReadBuildInfo
讀取內嵌在執行檔裡的建置資訊(
BuildInfo):Go 版本、主模組路徑與版本、所有依賴模組、建置設定(GOOS、CGO_ENABLED、版本控制的 commit 等)。第二個回傳值 ok 為 false 表示執行檔沒有這些資訊(例如不是以 module 模式建置)。常用來實作
--version 旗標,不必在建置時用 -ldflags 注入版本號。BuildInfo.Main.Version 的值:用 go install example.com/cmd@v1.2.3 安裝時是 v1.2.3;在 git 儲存庫中 go build 時,Go 1.24 起會依 tag 與 commit 產生版本號;不在版本控制下則是 (devel)。簽名:
- func ReadBuildInfo() (info *BuildInfo, ok bool)
範例:
- package main
- import (
- "fmt"
- "runtime/debug"
- )
- func main() {
- info, ok := debug.ReadBuildInfo()
- if !ok {
- fmt.Println("沒有建置資訊")
- return
- }
- fmt.Println("GoVersion:", info.GoVersion)
- fmt.Println("Path:", info.Path)
- fmt.Println("Main:", info.Main.Path, info.Main.Version)
- fmt.Println("依賴模組數:", len(info.Deps))
- for _, s := range info.Settings {
- switch s.Key {
- case "GOOS", "GOARCH", "CGO_ENABLED":
- fmt.Printf("%s=%s\n", s.Key, s.Value)
- }
- }
- }
輸出(依建置環境而異):
- GoVersion: go1.26.0
- Path: example.com/demo
- Main: example.com/demo (devel)
- 依賴模組數: 0
- CGO_ENABLED=1
- GOARCH=arm64
- GOOS=darwin
這個範例的
go.mod 是 module example.com/demo,沒有版本控制,所以版本是 (devel)。在 git 儲存庫中建置時,Settings 還會出現 vcs.revision(commit)、vcs.time、vcs.modified 等項目。SetGCPercent
設定 GC 的觸發比例,回傳舊值,效果等同啟動時設定
GOGC 環境變數。預設為 100:新配置的記憶體達到上次 GC 後存活資料的 100% 時,觸發下一次 GC。- 調大(如 200):GC 次數變少、CPU 負擔降低,但記憶體用量變多
- 調小(如 50):GC 更頻繁、記憶體用量較少
- 負數:關閉 GC(除非達到
SetMemoryLimit設定的上限)
大多數程式用預設值即可,調整前先用剖析工具確認 GC 真的是瓶頸。
簽名:
- func SetGCPercent(percent int) int
範例:
- package main
- import (
- "fmt"
- "runtime"
- "runtime/debug"
- )
- var sink []byte
- func countGC(percent int) uint32 {
- debug.SetGCPercent(percent)
- runtime.GC()
- var before, after runtime.MemStats
- runtime.ReadMemStats(&before)
- for range 2000 {
- sink = make([]byte, 64<<10)
- }
- runtime.ReadMemStats(&after)
- return after.NumGC - before.NumGC
- }
- func main() {
- fmt.Println("預設值:", debug.SetGCPercent(100))
- low := countGC(10)
- high := countGC(400)
- fmt.Println("GOGC=10 的 GC 次數比 GOGC=400 多:", low > high)
- off := countGC(-1)
- fmt.Println("關閉 GC 後的 GC 次數:", off)
- fmt.Println("恢復前的設定:", debug.SetGCPercent(100))
- }
輸出:
- 預設值: 100
- GOGC=10 的 GC 次數比 GOGC=400 多: true
- 關閉 GC 後的 GC 次數: 0
- 恢復前的設定: -1
實際 GC 次數依機器而異,範例只印出比較結果。
SetMemoryLimit
設定 Go runtime 的記憶體軟上限(soft limit,以位元組為單位),回傳舊值,效果等同
GOMEMLIMIT 環境變數。接近上限時 GC 會更積極地回收,盡量讓總記憶體不超過這個值;但若存活資料本身就超過上限,程式仍會繼續使用更多記憶體,不會因此被中止。傳入負數只查詢不修改。預設值是
math.MaxInt64,也就是沒有上限。常見搭配:在記憶體固定的容器裡,把上限設在容器限制的 80%~90% 左右,減少被系統 OOM(out of memory)終止的機會。
簽名:
- func SetMemoryLimit(limit int64) int64
範例:
- package main
- import (
- "fmt"
- "math"
- "runtime/debug"
- )
- func main() {
- cur := debug.SetMemoryLimit(-1)
- fmt.Println("預設沒有上限:", cur == math.MaxInt64)
- old := debug.SetMemoryLimit(512 << 20)
- fmt.Println("舊值是 MaxInt64:", old == math.MaxInt64)
- fmt.Println("目前上限 MiB:", debug.SetMemoryLimit(-1)>>20)
- }
輸出:
- 預設沒有上限: true
- 舊值是 MaxInt64: true
- 目前上限 MiB: 512
以環境變數設定:
GOMEMLIMIT=512MiB ./app。FreeOSMemory
強制執行一次 GC,並盡可能把空閒的記憶體還給作業系統。即使不呼叫,runtime 也會在背景慢慢歸還。適合在「一次性處理完大量資料、接下來會長時間閒置」的時機呼叫。
簽名:
- func FreeOSMemory()
範例:
- package main
- import (
- "fmt"
- "runtime"
- "runtime/debug"
- )
- var data [][]byte
- func main() {
- for range 200 {
- data = append(data, make([]byte, 1<<20))
- }
- data = nil
- var before, after runtime.MemStats
- runtime.ReadMemStats(&before)
- debug.FreeOSMemory()
- runtime.ReadMemStats(&after)
- fmt.Println("歸還給作業系統的記憶體增加:", after.HeapReleased > before.HeapReleased)
- fmt.Println("GC 次數增加:", after.NumGC > before.NumGC)
- }
輸出:
- 歸還給作業系統的記憶體增加: true
- GC 次數增加: true
HeapReleased 是已歸還給作業系統的堆積記憶體位元組數。ReadGCStats
把 GC 統計資料填進
GCStats:GC 次數(NumGC)、最近一次 GC 的時間(LastGC)、累計暫停時間(PauseTotal)、最近幾次的暫停時間(Pause,最新的在前面)。比 runtime.ReadMemStats 更專注在 GC 本身。簽名:
- func ReadGCStats(stats *GCStats)
範例:
- package main
- import (
- "fmt"
- "runtime"
- "runtime/debug"
- )
- func main() {
- var s debug.GCStats
- debug.ReadGCStats(&s)
- start := s.NumGC
- for range 3 {
- runtime.GC()
- }
- debug.ReadGCStats(&s)
- fmt.Println("新增 GC 次數:", s.NumGC-start)
- fmt.Println("有暫停紀錄:", len(s.Pause) > 0)
- fmt.Println("有最近 GC 時間:", !s.LastGC.IsZero())
- fmt.Println("累計暫停 >= 最近一次:", s.PauseTotal >= s.Pause[0])
- }
輸出:
- 新增 GC 次數: 3
- 有暫停紀錄: true
- 有最近 GC 時間: true
- 累計暫停 >= 最近一次: true
重點整理
debug.Stack()在recover後取得堆疊,記錄到 log 方便追查ReadBuildInfo讀取執行檔內嵌的 Go 版本、模組版本與 VCS 資訊,可直接用來做--versionSetGCPercent等同GOGC、SetMemoryLimit等同GOMEMLIMIT,兩者都回傳舊值;SetMemoryLimit(-1)只查詢FreeOSMemory立即歸還空閒記憶體,平常 runtime 會自動在背景處理- 調整 GC 參數前先剖析,確認 GC 真的是問題