Go支持GOGCTRACE环境变量,并在每次运行时打印收集统计信息。但它不会打印GC发生的时间。例如:
gc6231(8): 0+1+0 毫秒,10 -> 5 MB 89540 -> 5294 (520316701-520311407) 对象,9(80) 移交,32(404) 偷窃,288/168/37 产量
我该如何将收集行与其发生的时间相关联?
Go支持GOGCTRACE环境变量,并在每次运行时打印收集统计信息。但它不会打印GC发生的时间。例如:
gc6231(8): 0+1+0 毫秒,10 -> 5 MB 89540 -> 5294 (520316701-520311407) 对象,9(80) 移交,32(404) 偷窃,288/168/37 产量
我该如何将收集行与其发生的时间相关联?
GOGCTRACE=1 ./myprog 2>&1 | while read line; do echo $(date +%s) $line; done
runtime/debug
中的ReadGCStats
函数,它会给你GCStats
结构体,该结构体又有一个LastGC
字段,类型为time.Time
,保存着最后一次垃圾回收运行的绝对时间。或者你可以使用runtime.ReadMemStats
函数,它会给你更多信息。runtime.SetFinalizer
。在finalizer中,您将读取LastGC
时间并将其打印出来。type Garbage struct{ a int }
func notify(f *Garbage) {
stats := &runtime.MemStats{}
runtime.ReadMemStats(stats)
fmt.Println("Last GC was:", stats.LastGC)
go ProduceFinalizedGarbage()
}
func ProduceFinalizedGarbage() {
x := &Garbage{}
runtime.SetFinalizer(x, notify)
}
func main() {
go ProduceFinalizedGarbage()
for {
runtime.GC()
time.Sleep(30 * time.Second) // Give GC time to run
}
}
./myprog | while read line; do echo $(date +%s) $line; done
。 - nemo