github.com/puzpuzpuz/xsync/v2@v2.5.2-0.20231021165734-92b8269e19a9/util_test.go (about)

     1  package xsync_test
     2  
     3  import (
     4  	"hash/maphash"
     5  	"math/rand"
     6  	"testing"
     7  
     8  	. "github.com/puzpuzpuz/xsync/v2"
     9  )
    10  
    11  func TestNextPowOf2(t *testing.T) {
    12  	if NextPowOf2(0) != 1 {
    13  		t.Error("nextPowOf2 failed")
    14  	}
    15  	if NextPowOf2(1) != 1 {
    16  		t.Error("nextPowOf2 failed")
    17  	}
    18  	if NextPowOf2(2) != 2 {
    19  		t.Error("nextPowOf2 failed")
    20  	}
    21  	if NextPowOf2(3) != 4 {
    22  		t.Error("nextPowOf2 failed")
    23  	}
    24  }
    25  
    26  // This test is here to catch potential problems
    27  // with fastrand-related changes.
    28  func TestFastrand(t *testing.T) {
    29  	count := 100
    30  	set := make(map[uint32]struct{}, count)
    31  
    32  	for i := 0; i < count; i++ {
    33  		num := Fastrand()
    34  		set[num] = struct{}{}
    35  	}
    36  
    37  	if len(set) != count {
    38  		t.Error("duplicated rand num")
    39  	}
    40  }
    41  
    42  func BenchmarkFastrand(b *testing.B) {
    43  	for i := 0; i < b.N; i++ {
    44  		_ = Fastrand()
    45  	}
    46  	// about 1.4 ns/op on x86-64
    47  }
    48  
    49  func BenchmarkRand(b *testing.B) {
    50  	for i := 0; i < b.N; i++ {
    51  		_ = rand.Uint32()
    52  	}
    53  	// about 12 ns/op on x86-64
    54  }
    55  
    56  func BenchmarkMapHashString(b *testing.B) {
    57  	fn := func(seed maphash.Seed, s string) uint64 {
    58  		var h maphash.Hash
    59  		h.SetSeed(seed)
    60  		h.WriteString(s)
    61  		return h.Sum64()
    62  	}
    63  	seed := maphash.MakeSeed()
    64  	for i := 0; i < b.N; i++ {
    65  		_ = fn(seed, benchmarkKeyPrefix)
    66  	}
    67  	// about 13ns/op on x86-64
    68  }
    69  
    70  func BenchmarkHashString(b *testing.B) {
    71  	seed := maphash.MakeSeed()
    72  	for i := 0; i < b.N; i++ {
    73  		_ = HashString(seed, benchmarkKeyPrefix)
    74  	}
    75  	// about 4ns/op on x86-64
    76  }