GC Percent With debug.SetGCPercent
Change the GC growth target at runtime with debug.SetGCPercent, which returns the previous value, and inspect recorded pauses through debug.ReadGCStats.
Code
package main
import (
"fmt"
"runtime/debug"
"time"
)
func main() {
// SetGCPercent 返回旧值:先保存,收尾时还原
prev := debug.SetGCPercent(50)
fmt.Println("previous GOGC:", prev)
// 再设一次返回的就是当前生效值
fmt.Println("active GOGC:", debug.SetGCPercent(50))
// 还原,避免影响同一进程后续的分配节奏
defer debug.SetGCPercent(prev)
// ReadGCStats 填充分位数槽位;数值随运行环境变化,只当诊断看
var stats debug.GCStats
stats.PauseQuantiles = make([]time.Duration, 5)
debug.ReadGCStats(&stats)
fmt.Println("gc count so far:", stats.NumGC)
fmt.Println("pause samples:", len(stats.Pause))
fmt.Println("quantile slots:", len(stats.PauseQuantiles))
}How the snippet works
The snippet is organized around the function main.
Cleanup is attached with defer, so it runs on every exit path of the function.
Watch out for
- Zero third-party dependencies — the runtime provides every API used here.
Putting it to use
Entry signature: func main()
Printed lines carry labels — previous GOGC:, active GOGC:, gc count so far: — when the file runs.
Core lines
stats.PauseQuantiles = make([]time.Duration, 5)
defer debug.SetGCPercent(prev)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does GC Percent With debug.SetGCPercent print when run?
- Run it as a complete program — the output lines carry labels such as `previous GOGC:`, `active GOGC:`, `gc count so far:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.