Files
bulma/gc_advanced_diagnose.go
T

49 lines
1.1 KiB
Go
Raw 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 (
"log"
"net/http"
_ "net/http/pprof" // 注册pprof HTTP端点
"os"
"runtime"
"runtime/trace"
"time"
)
// simulateAlloc 模拟高频内存分配
func simulateAlloc() {
for {
_ = make([]byte, 1*1024*1024) // 每次分配1MB
time.Sleep(10 * time.Millisecond)
}
}
func main() {
// 1. 启动trace追踪,输出到文件
f, err := os.Create("gc_trace.out")
if err != nil {
log.Fatalf("创建trace文件失败: %v", err)
}
defer f.Close()
trace.Start(f)
defer trace.Stop()
// 2. 启动pprof HTTP服务(端口6060
go func() {
log.Println("pprof服务启动: http://localhost:6060/debug/pprof/")
log.Fatal(http.ListenAndServe(":6060", nil))
}()
// 3. 模拟内存分配压力
go simulateAlloc()
// 4. 运行30秒,积累诊断数据
log.Println("程序将运行30秒,可访问pprof分析GC...")
time.Sleep(30 * time.Second)
// 5. 打印最终GC状态
var stats runtime.MemStats
runtime.ReadMemStats(&stats)
log.Printf("运行结束,GC总次数: %d,累计STW时长: %d ms", stats.NumGC, stats.PauseTotalNs/1e6)
}