github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/testutils/memory.go (about)

     1  // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package testutils
     4  
     5  import (
     6  	"fmt"
     7  	timeutil "github.com/iwind/TeaGo/utils/time"
     8  	"runtime"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  func StartMemoryStatsGC(t *testing.T) {
    14  	var ticker = time.NewTicker(1 * time.Second)
    15  	go func() {
    16  		var stat = &runtime.MemStats{}
    17  		var lastHeapInUse uint64
    18  
    19  		for range ticker.C {
    20  			runtime.ReadMemStats(stat)
    21  			if stat.HeapInuse == lastHeapInUse {
    22  				return
    23  			}
    24  			lastHeapInUse = stat.HeapInuse
    25  
    26  			var before = time.Now()
    27  			runtime.GC()
    28  			var cost = time.Since(before).Seconds()
    29  
    30  			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")
    31  		}
    32  	}()
    33  }
    34  
    35  func StartMemoryStats(t *testing.T, callbacks ...func()) {
    36  	var ticker = time.NewTicker(1 * time.Second)
    37  	go func() {
    38  		var stat = &runtime.MemStats{}
    39  		var lastHeapInUse uint64
    40  
    41  		for range ticker.C {
    42  			runtime.ReadMemStats(stat)
    43  			if stat.HeapInuse == lastHeapInUse {
    44  				continue
    45  			}
    46  			lastHeapInUse = stat.HeapInuse
    47  
    48  			t.Log(timeutil.Format("H:i:s"), "HeapInuse:", fmt.Sprintf("%.2fM", float64(stat.HeapInuse)/1024/1024), "NumGC:", stat.NumGC)
    49  
    50  			if len(callbacks) > 0 {
    51  				for _, callback := range callbacks {
    52  					callback()
    53  				}
    54  			}
    55  		}
    56  	}()
    57  }
    58  
    59  func ReadMemoryStat() *runtime.MemStats {
    60  	var stat = &runtime.MemStats{}
    61  	runtime.ReadMemStats(stat)
    62  	return stat
    63  }