runtime_test.go 2.0 KB

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