实现说明
用 debug.SetGCPercent 调整 GC 频率可以归结为函数 main。
defer 预约了清理,无论函数怎么退出,预约的调用都会触发。
使用要点
- 每一步打印都带着自己的标签:
previous GOGC:、active GOGC:、gc count so far:。
常见问题
运行「用 debug.SetGCPercent 调整 GC 频率」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 previous GOGC:、active GOGC:、gc count so far: 标签标明各步骤。
核心语句
stats.PauseQuantiles = make([]time.Duration, 5)
defer debug.SetGCPercent(prev)
代码示例
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))
}