From 0d681a2e2954e1985b056c6bf67338fed759690f Mon Sep 17 00:00:00 2001 From: wanwu <609780590@qq.com> Date: Thu, 11 Sep 2025 21:56:07 +0800 Subject: [PATCH] opt: optimization of machine performance data reading (#5174) Co-authored-by: sam.yang --- core/prof/runtime.go | 27 ++++++++++++++++++++++++--- core/stat/usage.go | 29 +++++++++++++++++++++++++---- 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/core/prof/runtime.go b/core/prof/runtime.go index af41d0517..10554e56d 100644 --- a/core/prof/runtime.go +++ b/core/prof/runtime.go @@ -5,6 +5,8 @@ import ( "io" "os" "runtime" + "runtime/debug" + "runtime/metrics" "time" ) @@ -28,10 +30,29 @@ func displayStatsWithWriter(writer io.Writer, interval ...time.Duration) { ticker := time.NewTicker(duration) defer ticker.Stop() for range ticker.C { - var m runtime.MemStats - runtime.ReadMemStats(&m) + var ( + alloc, totalAlloc, sys uint64 + samples = []metrics.Sample{ + {Name: "/memory/classes/heap/objects:bytes"}, + {Name: "/gc/heap/allocs:bytes"}, + {Name: "/memory/classes/total:bytes"}, + } + ) + metrics.Read(samples) + + if samples[0].Value.Kind() == metrics.KindUint64 { + alloc = samples[0].Value.Uint64() + } + if samples[1].Value.Kind() == metrics.KindUint64 { + totalAlloc = samples[1].Value.Uint64() + } + if samples[2].Value.Kind() == metrics.KindUint64 { + sys = samples[2].Value.Uint64() + } + var stats debug.GCStats + debug.ReadGCStats(&stats) fmt.Fprintf(writer, "Goroutines: %d, Alloc: %vm, TotalAlloc: %vm, Sys: %vm, NumGC: %v\n", - runtime.NumGoroutine(), m.Alloc/mega, m.TotalAlloc/mega, m.Sys/mega, m.NumGC) + runtime.NumGoroutine(), alloc/mega, totalAlloc/mega, sys/mega, stats.NumGC) } }() } diff --git a/core/stat/usage.go b/core/stat/usage.go index 409366048..9bdecab76 100644 --- a/core/stat/usage.go +++ b/core/stat/usage.go @@ -1,7 +1,8 @@ package stat import ( - "runtime" + "runtime/debug" + "runtime/metrics" "sync/atomic" "time" @@ -56,8 +57,28 @@ func bToMb(b uint64) float32 { } func printUsage() { - var m runtime.MemStats - runtime.ReadMemStats(&m) + var ( + alloc, totalAlloc, sys uint64 + samples = []metrics.Sample{ + {Name: "/memory/classes/heap/objects:bytes"}, + {Name: "/gc/heap/allocs:bytes"}, + {Name: "/memory/classes/total:bytes"}, + } + stats debug.GCStats + ) + metrics.Read(samples) + + if samples[0].Value.Kind() == metrics.KindUint64 { + alloc = samples[0].Value.Uint64() + } + if samples[1].Value.Kind() == metrics.KindUint64 { + totalAlloc = samples[1].Value.Uint64() + } + if samples[2].Value.Kind() == metrics.KindUint64 { + sys = samples[2].Value.Uint64() + } + debug.ReadGCStats(&stats) + logx.Statf("CPU: %dm, MEMORY: Alloc=%.1fMi, TotalAlloc=%.1fMi, Sys=%.1fMi, NumGC=%d", - CpuUsage(), bToMb(m.Alloc), bToMb(m.TotalAlloc), bToMb(m.Sys), m.NumGC) + CpuUsage(), bToMb(alloc), bToMb(totalAlloc), bToMb(sys), stats.NumGC) }