github.com/maypok86/otter@v1.2.1/internal/stats/counter_bench_test.go (about)

     1  // Copyright (c) 2023 Alexey Mayshev. All rights reserved.
     2  // Copyright (c) 2021 Andrey Pechkurov
     3  //
     4  // Copyright notice. This code is a fork of benchmarks for xsync.Counter from this file with some changes:
     5  // https://github.com/puzpuzpuz/xsync/blob/main/counter_test.go
     6  //
     7  // Use of this source code is governed by a MIT license that can be found
     8  // at https://github.com/puzpuzpuz/xsync/blob/main/LICENSE
     9  
    10  package stats
    11  
    12  import (
    13  	"sync/atomic"
    14  	"testing"
    15  )
    16  
    17  func runBenchCounter(b *testing.B, value func() int64, increment func(), writeRatio int) {
    18  	b.Helper()
    19  	b.ResetTimer()
    20  	b.ReportAllocs()
    21  	b.RunParallel(func(pb *testing.PB) {
    22  		sink := 0
    23  		for pb.Next() {
    24  			sink++
    25  			if writeRatio > 0 && sink%writeRatio == 0 {
    26  				value()
    27  			} else {
    28  				increment()
    29  			}
    30  		}
    31  		_ = sink
    32  	})
    33  }
    34  
    35  func benchmarkCounter(b *testing.B, writeRatio int) {
    36  	b.Helper()
    37  	c := newCounter()
    38  	runBenchCounter(b, func() int64 {
    39  		return c.value()
    40  	}, func() {
    41  		c.increment()
    42  	}, writeRatio)
    43  }
    44  
    45  func BenchmarkCounter(b *testing.B) {
    46  	benchmarkCounter(b, 10000)
    47  }
    48  
    49  func benchmarkAtomicInt64(b *testing.B, writeRatio int) {
    50  	b.Helper()
    51  	var c int64
    52  	runBenchCounter(b, func() int64 {
    53  		return atomic.LoadInt64(&c)
    54  	}, func() {
    55  		atomic.AddInt64(&c, 1)
    56  	}, writeRatio)
    57  }
    58  
    59  func BenchmarkAtomicInt64(b *testing.B) {
    60  	benchmarkAtomicInt64(b, 10000)
    61  }