Files
bulma/sysmon_gc_demo.go

39 lines
915 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"fmt"
"runtime"
"runtime/debug"
"time"
)
func main() {
runtime.GC()
// 设置GOGC为一个非常大的值,相当于几乎不触发GC
oldGCPercent := debug.SetGCPercent(999999)
defer debug.SetGCPercent(oldGCPercent) // 恢复默认设置
printMemStats("初始状态")
// 分配 1GB 内存
var bigSlice [][]byte
for i := 0; i < 1024; i++ {
bigSlice = append(bigSlice, make([]byte, 1024*1024))
}
printMemStats("分配 1GB 内存后")
// 等待 sysmon 触发 GC(超 2 分钟)
fmt.Println("等待 sysmon 触发 GC125 秒)...")
time.Sleep(125 * time.Second)
printMemStats("sysmon 触发 GC 后")
fmt.Println("验证完成:内存占用回落,防止泄漏")
}
func printMemStats(stage string) {
var mStats runtime.MemStats
runtime.ReadMemStats(&mStats)
allocMB := mStats.Alloc / 1024 / 1024
fmt.Printf("[%s] 已分配内存:%d MB\n", stage, allocMB)
}