github.com/aitimate-0/go-ethereum@v1.9.7/metrics/runtime_test.go (about)

     1  package metrics
     2  
     3  import (
     4  	"runtime"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  func BenchmarkRuntimeMemStats(b *testing.B) {
    10  	r := NewRegistry()
    11  	RegisterRuntimeMemStats(r)
    12  	b.ResetTimer()
    13  	for i := 0; i < b.N; i++ {
    14  		CaptureRuntimeMemStatsOnce(r)
    15  	}
    16  }
    17  
    18  func TestRuntimeMemStats(t *testing.T) {
    19  	r := NewRegistry()
    20  	RegisterRuntimeMemStats(r)
    21  	CaptureRuntimeMemStatsOnce(r)
    22  	zero := runtimeMetrics.MemStats.PauseNs.Count() // Get a "zero" since GC may have run before these tests.
    23  	runtime.GC()
    24  	CaptureRuntimeMemStatsOnce(r)
    25  	if count := runtimeMetrics.MemStats.PauseNs.Count(); 1 != count-zero {
    26  		t.Fatal(count - zero)
    27  	}
    28  	runtime.GC()
    29  	runtime.GC()
    30  	CaptureRuntimeMemStatsOnce(r)
    31  	if count := runtimeMetrics.MemStats.PauseNs.Count(); 3 != count-zero {
    32  		t.Fatal(count - zero)
    33  	}
    34  	for i := 0; i < 256; i++ {
    35  		runtime.GC()
    36  	}
    37  	CaptureRuntimeMemStatsOnce(r)
    38  	if count := runtimeMetrics.MemStats.PauseNs.Count(); 259 != count-zero {
    39  		t.Fatal(count - zero)
    40  	}
    41  	for i := 0; i < 257; i++ {
    42  		runtime.GC()
    43  	}
    44  	CaptureRuntimeMemStatsOnce(r)
    45  	if count := runtimeMetrics.MemStats.PauseNs.Count(); 515 != count-zero { // We lost one because there were too many GCs between captures.
    46  		t.Fatal(count - zero)
    47  	}
    48  }
    49  
    50  func TestRuntimeMemStatsNumThread(t *testing.T) {
    51  	r := NewRegistry()
    52  	RegisterRuntimeMemStats(r)
    53  	CaptureRuntimeMemStatsOnce(r)
    54  
    55  	if value := runtimeMetrics.NumThread.Value(); value < 1 {
    56  		t.Fatalf("got NumThread: %d, wanted at least 1", value)
    57  	}
    58  }
    59  
    60  func TestRuntimeMemStatsBlocking(t *testing.T) {
    61  	if g := runtime.GOMAXPROCS(0); g < 2 {
    62  		t.Skipf("skipping TestRuntimeMemStatsBlocking with GOMAXPROCS=%d\n", g)
    63  	}
    64  	ch := make(chan int)
    65  	go testRuntimeMemStatsBlocking(ch)
    66  	var memStats runtime.MemStats
    67  	t0 := time.Now()
    68  	runtime.ReadMemStats(&memStats)
    69  	t1 := time.Now()
    70  	t.Log("i++ during runtime.ReadMemStats:", <-ch)
    71  	go testRuntimeMemStatsBlocking(ch)
    72  	d := t1.Sub(t0)
    73  	t.Log(d)
    74  	time.Sleep(d)
    75  	t.Log("i++ during time.Sleep:", <-ch)
    76  }
    77  
    78  func testRuntimeMemStatsBlocking(ch chan int) {
    79  	i := 0
    80  	for {
    81  		select {
    82  		case ch <- i:
    83  			return
    84  		default:
    85  			i++
    86  		}
    87  	}
    88  }