github.com/zeebo/mon@v0.0.0-20211012163247-13d39bdb54fa/state_test.go (about)

     1  package mon
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  	"sync/atomic"
     7  	"testing"
     8  )
     9  
    10  func BenchmarkGetState(b *testing.B) {
    11  	var sink *State
    12  	b.ReportAllocs()
    13  
    14  	for i := 0; i < b.N; i++ {
    15  		sink = GetState("foo")
    16  	}
    17  
    18  	runtime.KeepAlive(sink)
    19  }
    20  
    21  func BenchmarkState(b *testing.B) {
    22  	b.Run("Observe", func(b *testing.B) {
    23  		b.ReportAllocs()
    24  
    25  		for i := 0; i < b.N; i++ {
    26  			GetState("bench").Histogram().Observe(1)
    27  		}
    28  	})
    29  
    30  	b.Run("Observe_Parallel", func(b *testing.B) {
    31  		var n uint64
    32  		b.RunParallel(func(pb *testing.PB) {
    33  			metric := fmt.Sprintf("bench-%d", atomic.AddUint64(&n, 1))
    34  			for pb.Next() {
    35  				GetState(metric).Histogram().Observe(1)
    36  			}
    37  		})
    38  	})
    39  }