Files
EdgeNode/internal/utils/testutils/memory.go

65 lines
1.4 KiB
Go
Raw Normal View History

2024-05-17 18:30:33 +08:00
// Copyright 2022 GoEdge goedge.cdn@gmail.com. All rights reserved.
2022-03-12 18:00:22 +08:00
package testutils
import (
"fmt"
"runtime"
"testing"
"time"
2024-07-27 15:42:50 +08:00
timeutil "github.com/iwind/TeaGo/utils/time"
2022-03-12 18:00:22 +08:00
)
2022-03-20 10:48:11 +08:00
func StartMemoryStatsGC(t *testing.T) {
2022-03-12 18:00:22 +08:00
var ticker = time.NewTicker(1 * time.Second)
go func() {
var stat = &runtime.MemStats{}
var lastHeapInUse uint64
for range ticker.C {
runtime.ReadMemStats(stat)
if stat.HeapInuse == lastHeapInUse {
return
}
lastHeapInUse = stat.HeapInuse
var before = time.Now()
runtime.GC()
var cost = time.Since(before).Seconds()
t.Log(timeutil.Format("H:i:s"), "HeapInuse:", fmt.Sprintf("%.2fM", float64(stat.HeapInuse)/1024/1024), "NumGC:", stat.NumGC, "Cost:", fmt.Sprintf("%.4f", cost*1000), "ms")
}
}()
}
2022-03-20 10:48:11 +08:00
func StartMemoryStats(t *testing.T, callbacks ...func()) {
2022-03-20 10:48:11 +08:00
var ticker = time.NewTicker(1 * time.Second)
go func() {
var stat = &runtime.MemStats{}
var lastHeapInUse uint64
for range ticker.C {
runtime.ReadMemStats(stat)
if stat.HeapInuse == lastHeapInUse {
2023-10-05 08:41:07 +08:00
continue
2022-03-20 10:48:11 +08:00
}
lastHeapInUse = stat.HeapInuse
t.Log(timeutil.Format("H:i:s"), "HeapInuse:", fmt.Sprintf("%.2fM", float64(stat.HeapInuse)/1024/1024), "NumGC:", stat.NumGC)
if len(callbacks) > 0 {
for _, callback := range callbacks {
callback()
}
}
2022-03-20 10:48:11 +08:00
}
}()
}
func ReadMemoryStat() *runtime.MemStats {
var stat = &runtime.MemStats{}
runtime.ReadMemStats(stat)
return stat
}