| 1 |
// Copyright 2020-23 The LevelDB-Go, Pebble and NATS Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style license that can be found in |
| 3 |
// the LICENSE file. |
| 4 |
|
| 5 |
package fastrand |
| 6 |
|
| 7 |
import ( |
| 8 |
"math/rand" |
| 9 |
"sync" |
| 10 |
"testing" |
| 11 |
"time" |
| 12 |
) |
| 13 |
|
| 14 |
type defaultRand struct { |
| 15 |
mu sync.Mutex |
| 16 |
src rand.Source64 |
| 17 |
} |
| 18 |
|
| 19 |
func newDefaultRand() *defaultRand { |
| 20 |
r := &defaultRand{ |
| 21 |
src: rand.New(rand.NewSource(time.Now().UnixNano())), |
| 22 |
} |
| 23 |
return r |
| 24 |
} |
| 25 |
|
| 26 |
func (r *defaultRand) Uint32() uint32 { |
| 27 |
r.mu.Lock() |
| 28 |
i := uint32(r.src.Uint64()) |
| 29 |
r.mu.Unlock() |
| 30 |
return i |
| 31 |
} |
| 32 |
|
| 33 |
func (r *defaultRand) Uint64() uint64 { |
| 34 |
r.mu.Lock() |
| 35 |
i := uint64(r.src.Uint64()) |
| 36 |
r.mu.Unlock() |
| 37 |
return i |
| 38 |
} |
| 39 |
|
| 40 |
func BenchmarkFastRand32(b *testing.B) { |
| 41 |
b.RunParallel(func(pb *testing.PB) { |
| 42 |
for pb.Next() { |
| 43 |
Uint32() |
| 44 |
} |
| 45 |
}) |
| 46 |
} |
| 47 |
|
| 48 |
func BenchmarkFastRand64(b *testing.B) { |
| 49 |
b.RunParallel(func(pb *testing.PB) { |
| 50 |
for pb.Next() { |
| 51 |
Uint64() |
| 52 |
} |
| 53 |
}) |
| 54 |
} |
| 55 |
|
| 56 |
func BenchmarkDefaultRand32(b *testing.B) { |
| 57 |
r := newDefaultRand() |
| 58 |
b.RunParallel(func(pb *testing.PB) { |
| 59 |
for pb.Next() { |
| 60 |
r.Uint32() |
| 61 |
} |
| 62 |
}) |
| 63 |
} |
| 64 |
|
| 65 |
func BenchmarkDefaultRand64(b *testing.B) { |
| 66 |
r := newDefaultRand() |
| 67 |
b.RunParallel(func(pb *testing.PB) { |
| 68 |
for pb.Next() { |
| 69 |
r.Uint64() |
| 70 |
} |
| 71 |
}) |
| 72 |
} |