github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/internal/fastrand/fastrand_test.go (about)

     1  // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package fastrand
    16  
    17  import (
    18  	"fmt"
    19  	"sync"
    20  	"testing"
    21  	"time"
    22  
    23  	"golang.org/x/exp/rand"
    24  )
    25  
    26  type defaultRand struct {
    27  	mu  sync.Mutex
    28  	src rand.PCGSource
    29  }
    30  
    31  func newDefaultRand() *defaultRand {
    32  	r := &defaultRand{}
    33  	r.src.Seed(uint64(time.Now().UnixNano()))
    34  	return r
    35  }
    36  
    37  func (r *defaultRand) Uint32() uint32 {
    38  	r.mu.Lock()
    39  	i := uint32(r.src.Uint64())
    40  	r.mu.Unlock()
    41  	return i
    42  }
    43  
    44  func BenchmarkFastRand(b *testing.B) {
    45  	b.RunParallel(func(pb *testing.PB) {
    46  		for pb.Next() {
    47  			Uint32()
    48  		}
    49  	})
    50  }
    51  
    52  func BenchmarkDefaultRand(b *testing.B) {
    53  	r := newDefaultRand()
    54  	b.RunParallel(func(pb *testing.PB) {
    55  		for pb.Next() {
    56  			r.Uint32()
    57  		}
    58  	})
    59  }
    60  
    61  var xg uint32
    62  
    63  func BenchmarkSTFastRand(b *testing.B) {
    64  	var x uint32
    65  	for i := 0; i < b.N; i++ {
    66  		x = Uint32n(2097152)
    67  	}
    68  	xg = x
    69  }
    70  
    71  func BenchmarkSTDefaultRand(b *testing.B) {
    72  	for _, newPeriod := range []int{0, 10, 100, 1000} {
    73  		name := "no-new"
    74  		if newPeriod > 0 {
    75  			name = fmt.Sprintf("new-period=%d", newPeriod)
    76  		}
    77  		b.Run(name, func(b *testing.B) {
    78  			r := rand.New(rand.NewSource(uint64(time.Now().UnixNano())))
    79  			b.ResetTimer()
    80  			var x uint32
    81  			for i := 0; i < b.N; i++ {
    82  				if newPeriod > 0 && i%newPeriod == 0 {
    83  					r = rand.New(rand.NewSource(uint64(time.Now().UnixNano())))
    84  				}
    85  				x = uint32(r.Uint64n(2097152))
    86  			}
    87  			xg = x
    88  		})
    89  	}
    90  }