github.com/go-eden/common@v0.1.15-0.20210617133546-059099253264/esync/sync_atomic_int_test.go (about)

     1  package esync
     2  
     3  import (
     4  	"github.com/stretchr/testify/assert"
     5  	"math/rand"
     6  	"testing"
     7  )
     8  
     9  func TestAtomicInt(t *testing.T) {
    10  	var num AtomicInt
    11  
    12  	assert.True(t, num.Inc() == 1)
    13  	assert.True(t, num.Add(2) == 3)
    14  	num.Set(100)
    15  	assert.True(t, num.Swap(200) == 100)
    16  	assert.True(t, num.Get() == 200)
    17  
    18  	num.Set(0)
    19  	for i := 1; i < 200000; i++ {
    20  		assert.True(t, num.Add(1) == i)
    21  	}
    22  	multiRun(5, func() {
    23  		for i := 0; i < 200000; i++ {
    24  			num.Set(100)
    25  			_ = num.Swap(200)
    26  			num.Get()
    27  		}
    28  	})
    29  }
    30  
    31  // BenchmarkAtomicInt_Add-12    	251870193	         4.817 ns/op
    32  func BenchmarkAtomicInt_Add(b *testing.B) {
    33  	var num AtomicInt
    34  	for i := 0; i < b.N; i++ {
    35  		num.Add(i)
    36  	}
    37  }
    38  
    39  // BenchmarkAtomicInt_Get-12    	1000000000	         0.3167 ns/op
    40  func BenchmarkAtomicInt_Get(b *testing.B) {
    41  	var num AtomicInt
    42  	num.Set(rand.Int())
    43  	for i := 0; i < b.N; i++ {
    44  		num.Get()
    45  	}
    46  }
    47  
    48  // BenchmarkAtomicIntAll-12    	128318323	         9.233 ns/op
    49  func BenchmarkAtomicIntAll(b *testing.B) {
    50  	var num AtomicInt
    51  
    52  	for i := 0; i < b.N; i++ {
    53  		num.Inc()
    54  		_ = num.Swap(i)
    55  	}
    56  }