github.com/xaionaro-go/rand@v0.0.0-20191005105903-aba1befc54a5/mathrand/uintxn_test.go (about)

     1  package mathrand_test
     2  
     3  import (
     4  	"math/rand"
     5  	"testing"
     6  	"time"
     7  	"unsafe"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  	valyala "github.com/valyala/fastrand"
    11  	nebulousLabs "gitlab.com/NebulousLabs/fastrand"
    12  	lukechampine "lukechampine.com/frand"
    13  
    14  	"github.com/xaionaro-go/rand/mathrand"
    15  )
    16  
    17  func BenchmarkStandardIntn(b *testing.B) {
    18  	b.SetBytes(int64(unsafe.Sizeof(int(0))))
    19  	for i := 0; i < b.N; i++ {
    20  		rand.Intn(1000)
    21  	}
    22  }
    23  
    24  func BenchmarkValyalaUint32n(b *testing.B) {
    25  	b.SetBytes(4)
    26  	for i := 0; i < b.N; i++ {
    27  		valyala.Uint32n(1000)
    28  	}
    29  }
    30  
    31  func BenchmarkValyalaUint32n_withPreparedRNG(b *testing.B) {
    32  	prng := &valyala.RNG{}
    33  	b.SetBytes(4)
    34  	b.ResetTimer()
    35  	for i := 0; i < b.N; i++ {
    36  		prng.Uint32n(1000)
    37  	}
    38  }
    39  
    40  func BenchmarkNebulousLabsIntn(b *testing.B) {
    41  	b.SetBytes(int64(unsafe.Sizeof(int(0))))
    42  	for i := 0; i < b.N; i++ {
    43  		nebulousLabs.Intn(1000)
    44  	}
    45  }
    46  
    47  func BenchmarkLukechampineUint64n(b *testing.B) {
    48  	b.SetBytes(8)
    49  	for i := 0; i < b.N; i++ {
    50  		lukechampine.Uint64n(1000)
    51  	}
    52  }
    53  
    54  func BenchmarkTimeNowUnixNano(b *testing.B) {
    55  	b.SetBytes(8)
    56  	for i := 0; i < b.N; i++ {
    57  		time.Now().UnixNano()
    58  	}
    59  }
    60  
    61  func testUint32(t *testing.T, fn func() uint32) {
    62  	var count int
    63  	for i := 0; i < 1000; i++ {
    64  		if mathrand.ReduceUint32(fn(), 4) == 0 {
    65  			count++
    66  		}
    67  	}
    68  	assert.True(t, count > 220, count)
    69  	assert.True(t, count < 280, count)
    70  
    71  	for i := 0; i < 9000; i++ {
    72  		if mathrand.ReduceUint32(fn(), 4) == 0 {
    73  			count++
    74  		}
    75  	}
    76  	assert.True(t, count > 2300, count)
    77  	assert.True(t, count < 2700, count)
    78  }
    79  
    80  func testUint64(t *testing.T, fn func() uint64) {
    81  	var count int
    82  	for i := 0; i < 1000; i++ {
    83  		if mathrand.ReduceUint64(fn(), 4) == 0 {
    84  			count++
    85  		}
    86  	}
    87  	assert.True(t, count > 220, count)
    88  	assert.True(t, count < 280, count)
    89  
    90  	for i := 0; i < 9000; i++ {
    91  		if mathrand.ReduceUint64(fn(), 4) == 0 {
    92  			count++
    93  		}
    94  	}
    95  	assert.True(t, count > 2300, count)
    96  	assert.True(t, count < 2700, count)
    97  }