-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrandom_bounded_test.go
51 lines (45 loc) · 1.11 KB
/
random_bounded_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"math/rand"
"testing"
"time"
)
const rangeBound int32 = 1357
var globalVar int32
func BenchmarkStandardBoundedRandomNumber(b *testing.B) {
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
b.ResetTimer()
for n := 0; n < b.N; n++ {
globalVar = r.Int31n(rangeBound)
}
}
func BenchmarkBiasedFastBoundedRandomNumber(b *testing.B) {
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
b.ResetTimer()
for n := 0; n < b.N; n++ {
random := int64(r.Int31())
multiResult := random * int64(rangeBound)
globalVar = int32(multiResult >> 32)
}
}
func BenchmarkUnbiasedFastBoundedRandomNumber(b *testing.B) {
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
b.ResetTimer()
for n := 0; n < b.N; n++ {
random := int64(r.Int31())
multiResult := random * int64(rangeBound)
leftover := int32(multiResult)
if leftover < rangeBound {
threshold := -rangeBound % rangeBound
for leftover < threshold {
random = int64(r.Int31())
multiResult = random * int64(rangeBound)
leftover = int32(multiResult)
}
}
globalVar = int32(multiResult >> 32)
}
}