runtime/debug

最後更新


runtime/debug 套件提供程式在執行中「自我檢查與調整」的工具:取得堆疊追蹤、讀取建置資訊、調整垃圾回收與記憶體上限。

這個套件做什麼


runtime 處理日常的執行環境查詢,runtime/debug 則收錄比較偏維運與除錯的功能:
想做的事API
recover 之後把堆疊記進 logStack、PrintStack
印出版本號、commit、依賴模組ReadBuildInfo
調整 GC 頻率(等同 GOGC 環境變數)SetGCPercent
設定記憶體軟上限(等同 GOMEMLIMIT)SetMemoryLimit
立刻把空閒記憶體還給作業系統FreeOSMemory
讀取 GC 次數與暫停時間ReadGCStats

GC 的運作與 GOGC、GOMEMLIMIT 的觀念見 記憶體與 GC;效能剖析請用 runtime/pprof。
注意:部分輸出依機器與建置方式而異,本頁範例是在本機 go1.26.0、darwin/arm64,以 go build 建置後執行的結果。

匯入


  1. import "runtime/debug"

常用 API


Stack 與 PrintStack


  • Stack():回傳呼叫它的 goroutine 目前的堆疊追蹤(stack trace),格式與 panic 時印出的相同
  • PrintStack():直接把同樣的內容印到標準錯誤輸出(stderr)

最常見的用途是在 recover 之後記錄堆疊,這樣程式不會崩潰,事後也查得到是哪裡出錯(觀念見 panic 與 recover)。
堆疊內容包含原始檔的完整路徑與記憶體偏移量,每台機器都不同,範例只挑出函式名稱那幾行。
簽名:
  1. func Stack() []byte
  2. func PrintStack()

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "runtime/debug"
  5. "strings"
  6. )
  7. func safeRun(f func()) {
  8. defer func() {
  9. if r := recover(); r != nil {
  10. fmt.Println("recovered:", r)
  11. for _, line := range strings.Split(string(debug.Stack()), "\n") {
  12. if strings.HasPrefix(line, "main.") || strings.HasPrefix(line, "goroutine ") {
  13. fmt.Println(" ", line[:strings.IndexAny(line, "(:")])
  14. }
  15. }
  16. }
  17. }()
  18. f()
  19. }
  20. func divide(a, b int) int {
  21. return a / b
  22. }
  23. func main() {
  24. safeRun(func() {
  25. fmt.Println(divide(10, 0))
  26. })
  27. fmt.Println("程式繼續執行")
  28. }

輸出:
  1. recovered: runtime error: integer divide by zero
  2. goroutine 1 [running]
  3. main.safeRun.func1
  4. main.divide
  5. main.main.func1
  6. main.safeRun
  7. main.main
  8. 程式繼續執行

堆疊由內往外列出。篩選掉 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)。
簽名:
  1. func ReadBuildInfo() (info *BuildInfo, ok bool)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "runtime/debug"
  5. )
  6. func main() {
  7. info, ok := debug.ReadBuildInfo()
  8. if !ok {
  9. fmt.Println("沒有建置資訊")
  10. return
  11. }
  12. fmt.Println("GoVersion:", info.GoVersion)
  13. fmt.Println("Path:", info.Path)
  14. fmt.Println("Main:", info.Main.Path, info.Main.Version)
  15. fmt.Println("依賴模組數:", len(info.Deps))
  16. for _, s := range info.Settings {
  17. switch s.Key {
  18. case "GOOS", "GOARCH", "CGO_ENABLED":
  19. fmt.Printf("%s=%s\n", s.Key, s.Value)
  20. }
  21. }
  22. }

輸出(依建置環境而異):
  1. GoVersion: go1.26.0
  2. Path: example.com/demo
  3. Main: example.com/demo (devel)
  4. 依賴模組數: 0
  5. CGO_ENABLED=1
  6. GOARCH=arm64
  7. 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 真的是瓶頸。
簽名:
  1. func SetGCPercent(percent int) int

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. "runtime/debug"
  6. )
  7. var sink []byte
  8. func countGC(percent int) uint32 {
  9. debug.SetGCPercent(percent)
  10. runtime.GC()
  11. var before, after runtime.MemStats
  12. runtime.ReadMemStats(&before)
  13. for range 2000 {
  14. sink = make([]byte, 64<<10)
  15. }
  16. runtime.ReadMemStats(&after)
  17. return after.NumGC - before.NumGC
  18. }
  19. func main() {
  20. fmt.Println("預設值:", debug.SetGCPercent(100))
  21. low := countGC(10)
  22. high := countGC(400)
  23. fmt.Println("GOGC=10 的 GC 次數比 GOGC=400 多:", low > high)
  24. off := countGC(-1)
  25. fmt.Println("關閉 GC 後的 GC 次數:", off)
  26. fmt.Println("恢復前的設定:", debug.SetGCPercent(100))
  27. }

輸出:
  1. 預設值: 100
  2. GOGC=10 的 GC 次數比 GOGC=400 多: true
  3. 關閉 GC 後的 GC 次數: 0
  4. 恢復前的設定: -1

實際 GC 次數依機器而異,範例只印出比較結果。

SetMemoryLimit


設定 Go runtime 的記憶體軟上限(soft limit,以位元組為單位),回傳舊值,效果等同 GOMEMLIMIT 環境變數。接近上限時 GC 會更積極地回收,盡量讓總記憶體不超過這個值;但若存活資料本身就超過上限,程式仍會繼續使用更多記憶體,不會因此被中止。
傳入負數只查詢不修改。預設值是 math.MaxInt64,也就是沒有上限。
常見搭配:在記憶體固定的容器裡,把上限設在容器限制的 80%~90% 左右,減少被系統 OOM(out of memory)終止的機會。
簽名:
  1. func SetMemoryLimit(limit int64) int64

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "runtime/debug"
  6. )
  7. func main() {
  8. cur := debug.SetMemoryLimit(-1)
  9. fmt.Println("預設沒有上限:", cur == math.MaxInt64)
  10. old := debug.SetMemoryLimit(512 << 20)
  11. fmt.Println("舊值是 MaxInt64:", old == math.MaxInt64)
  12. fmt.Println("目前上限 MiB:", debug.SetMemoryLimit(-1)>>20)
  13. }

輸出:
  1. 預設沒有上限: true
  2. 舊值是 MaxInt64: true
  3. 目前上限 MiB: 512

以環境變數設定:GOMEMLIMIT=512MiB ./app。

FreeOSMemory


強制執行一次 GC,並盡可能把空閒的記憶體還給作業系統。即使不呼叫,runtime 也會在背景慢慢歸還。適合在「一次性處理完大量資料、接下來會長時間閒置」的時機呼叫。
簽名:
  1. func FreeOSMemory()

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. "runtime/debug"
  6. )
  7. var data [][]byte
  8. func main() {
  9. for range 200 {
  10. data = append(data, make([]byte, 1<<20))
  11. }
  12. data = nil
  13. var before, after runtime.MemStats
  14. runtime.ReadMemStats(&before)
  15. debug.FreeOSMemory()
  16. runtime.ReadMemStats(&after)
  17. fmt.Println("歸還給作業系統的記憶體增加:", after.HeapReleased > before.HeapReleased)
  18. fmt.Println("GC 次數增加:", after.NumGC > before.NumGC)
  19. }

輸出:
  1. 歸還給作業系統的記憶體增加: true
  2. GC 次數增加: true

HeapReleased 是已歸還給作業系統的堆積記憶體位元組數。

ReadGCStats


把 GC 統計資料填進 GCStats:GC 次數(NumGC)、最近一次 GC 的時間(LastGC)、累計暫停時間(PauseTotal)、最近幾次的暫停時間(Pause,最新的在前面)。比 runtime.ReadMemStats 更專注在 GC 本身。
簽名:
  1. func ReadGCStats(stats *GCStats)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. "runtime/debug"
  6. )
  7. func main() {
  8. var s debug.GCStats
  9. debug.ReadGCStats(&s)
  10. start := s.NumGC
  11. for range 3 {
  12. runtime.GC()
  13. }
  14. debug.ReadGCStats(&s)
  15. fmt.Println("新增 GC 次數:", s.NumGC-start)
  16. fmt.Println("有暫停紀錄:", len(s.Pause) > 0)
  17. fmt.Println("有最近 GC 時間:", !s.LastGC.IsZero())
  18. fmt.Println("累計暫停 >= 最近一次:", s.PauseTotal >= s.Pause[0])
  19. }

輸出:
  1. 新增 GC 次數: 3
  2. 有暫停紀錄: true
  3. 有最近 GC 時間: true
  4. 累計暫停 >= 最近一次: true

重點整理


  • debug.Stack() 在 recover 後取得堆疊,記錄到 log 方便追查
  • ReadBuildInfo 讀取執行檔內嵌的 Go 版本、模組版本與 VCS 資訊,可直接用來做 --version
  • SetGCPercent 等同 GOGC、SetMemoryLimit 等同 GOMEMLIMIT,兩者都回傳舊值;SetMemoryLimit(-1) 只查詢
  • FreeOSMemory 立即歸還空閒記憶體,平常 runtime 會自動在背景處理
  • 調整 GC 參數前先剖析,確認 GC 真的是問題

資料來源