github.com/puzpuzpuz/xsync/v3@v3.1.1-0.20240225193106-cbe4ec1e954f/util_test.go (about)

     1  package xsync_test
     2  
     3  import (
     4  	"math/rand"
     5  	"testing"
     6  
     7  	. "github.com/puzpuzpuz/xsync/v3"
     8  )
     9  
    10  func TestNextPowOf2(t *testing.T) {
    11  	if NextPowOf2(0) != 1 {
    12  		t.Error("nextPowOf2 failed")
    13  	}
    14  	if NextPowOf2(1) != 1 {
    15  		t.Error("nextPowOf2 failed")
    16  	}
    17  	if NextPowOf2(2) != 2 {
    18  		t.Error("nextPowOf2 failed")
    19  	}
    20  	if NextPowOf2(3) != 4 {
    21  		t.Error("nextPowOf2 failed")
    22  	}
    23  }
    24  
    25  // This test is here to catch potential problems
    26  // with fastrand-related changes.
    27  func TestFastrand(t *testing.T) {
    28  	count := 100
    29  	set := make(map[uint32]struct{}, count)
    30  
    31  	for i := 0; i < count; i++ {
    32  		num := Fastrand()
    33  		set[num] = struct{}{}
    34  	}
    35  
    36  	if len(set) != count {
    37  		t.Error("duplicated rand num")
    38  	}
    39  }
    40  
    41  func BenchmarkFastrand(b *testing.B) {
    42  	for i := 0; i < b.N; i++ {
    43  		_ = Fastrand()
    44  	}
    45  	// about 1.4 ns/op on x86-64
    46  }
    47  
    48  func BenchmarkRand(b *testing.B) {
    49  	for i := 0; i < b.N; i++ {
    50  		_ = rand.Uint32()
    51  	}
    52  	// about 12 ns/op on x86-64
    53  }