Skip to content

Commit

Permalink
fastrand: optimize Uint32N()
Browse files Browse the repository at this point in the history
name                old time/op  new time/op  delta
FastRandBuf-16      32.5ns ± 4%  18.8ns ± 7%  -42.02%  (p=0.000 n=9+10)
FastRandUint32N-16  0.91ns ± 1%  0.19ns ±12%  -78.83%  (p=0.000 n=9+10)

ref #33239
  • Loading branch information
zhangyunhao116 committed Mar 18, 2022
1 parent a304490 commit de15b2b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
7 changes: 3 additions & 4 deletions util/fastrand/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,9 @@ func Uint32() uint32

// Uint32N returns, as an uint32, a pseudo-random number in [0,n).
func Uint32N(n uint32) uint32 {
if n&(n-1) == 0 { // n is power of two, can mask
return Uint32() & (n - 1)
}
return Uint32() % n
// This is similar to Uint32() % n, but faster.
// See https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
return uint32(uint64(Uint32()) * uint64(n) >> 32)
}

// Uint64N returns, as an uint64, a pseudo-random number in [0,n).
Expand Down
16 changes: 16 additions & 0 deletions util/fastrand/random_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,22 @@ func TestRand(t *testing.T) {
require.Less(t, sum, 24)
}

func BenchmarkFastRandBuf(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Buf(20)
}
})
}

func BenchmarkFastRandUint32N(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Uint32N(127)
}
})
}

func BenchmarkFastRand(b *testing.B) {
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
Expand Down

0 comments on commit de15b2b

Please sign in to comment.