github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/metrics/runtime_test.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 19:16:40</date> 10 //</624450100025888768> 11 12 package metrics 13 14 import ( 15 "runtime" 16 "testing" 17 "time" 18 ) 19 20 func BenchmarkRuntimeMemStats(b *testing.B) { 21 r := NewRegistry() 22 RegisterRuntimeMemStats(r) 23 b.ResetTimer() 24 for i := 0; i < b.N; i++ { 25 CaptureRuntimeMemStatsOnce(r) 26 } 27 } 28 29 func TestRuntimeMemStats(t *testing.T) { 30 r := NewRegistry() 31 RegisterRuntimeMemStats(r) 32 CaptureRuntimeMemStatsOnce(r) 33 zero := runtimeMetrics.MemStats.PauseNs.Count() //得到一个“零”,因为GC可能在这些测试之前运行。 34 runtime.GC() 35 CaptureRuntimeMemStatsOnce(r) 36 if count := runtimeMetrics.MemStats.PauseNs.Count(); 1 != count-zero { 37 t.Fatal(count - zero) 38 } 39 runtime.GC() 40 runtime.GC() 41 CaptureRuntimeMemStatsOnce(r) 42 if count := runtimeMetrics.MemStats.PauseNs.Count(); 3 != count-zero { 43 t.Fatal(count - zero) 44 } 45 for i := 0; i < 256; i++ { 46 runtime.GC() 47 } 48 CaptureRuntimeMemStatsOnce(r) 49 if count := runtimeMetrics.MemStats.PauseNs.Count(); 259 != count-zero { 50 t.Fatal(count - zero) 51 } 52 for i := 0; i < 257; i++ { 53 runtime.GC() 54 } 55 CaptureRuntimeMemStatsOnce(r) 56 if count := runtimeMetrics.MemStats.PauseNs.Count(); 515 != count-zero { //我们丢失了一个,因为捕获之间的GCS太多了。 57 t.Fatal(count - zero) 58 } 59 } 60 61 func TestRuntimeMemStatsNumThread(t *testing.T) { 62 r := NewRegistry() 63 RegisterRuntimeMemStats(r) 64 CaptureRuntimeMemStatsOnce(r) 65 66 if value := runtimeMetrics.NumThread.Value(); value < 1 { 67 t.Fatalf("got NumThread: %d, wanted at least 1", value) 68 } 69 } 70 71 func TestRuntimeMemStatsBlocking(t *testing.T) { 72 if g := runtime.GOMAXPROCS(0); g < 2 { 73 t.Skipf("skipping TestRuntimeMemStatsBlocking with GOMAXPROCS=%d\n", g) 74 } 75 ch := make(chan int) 76 go testRuntimeMemStatsBlocking(ch) 77 var memStats runtime.MemStats 78 t0 := time.Now() 79 runtime.ReadMemStats(&memStats) 80 t1 := time.Now() 81 t.Log("i++ during runtime.ReadMemStats:", <-ch) 82 go testRuntimeMemStatsBlocking(ch) 83 d := t1.Sub(t0) 84 t.Log(d) 85 time.Sleep(d) 86 t.Log("i++ during time.Sleep:", <-ch) 87 } 88 89 func testRuntimeMemStatsBlocking(ch chan int) { 90 i := 0 91 for { 92 select { 93 case ch <- i: 94 return 95 default: 96 i++ 97 } 98 } 99 } 100