-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrandish_test.go
84 lines (66 loc) · 1.56 KB
/
randish_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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package randish_test
import (
"sync"
"testing"
"github.com/TechMDW/randish"
)
func TestSeed(t *testing.T) {
const numIterations = 100000
duplicates := sync.Map{}
for i := 0; i < numIterations; i++ {
seed := randish.Seed()
_, loaded := duplicates.LoadOrStore(seed, true)
if loaded {
t.Fatalf("Found duplicate number %d after %d iterations", seed, i)
}
}
}
func TestSeedParallel(t *testing.T) {
const numIterations = 2000000
const numWorkers = 50
duplicates := make(map[int64]bool)
var mu sync.Mutex
lim := make(chan struct{}, numWorkers)
wg := sync.WaitGroup{}
for i := 0; i < numIterations; i++ {
lim <- struct{}{}
wg.Add(1)
go func(i int) {
defer func() {
<-lim
wg.Done()
}()
seed := randish.Seed()
mu.Lock()
if duplicates[seed] {
t.Errorf("Found duplicate number %d after %d iterations", seed, i)
}
duplicates[seed] = true
mu.Unlock()
}(i)
}
wg.Wait()
}
func TestDistribution(t *testing.T) {
const numIterations = 100000
const numValues = 2
const tolerance = 0.01
counts := make([]int, numValues)
r := randish.Rand()
for i := 0; i < numIterations; i++ {
value := r.Intn(numValues)
counts[value]++
}
for i, count := range counts {
percent := float64(count) / float64(numIterations)
if percent < 1.0/numValues-tolerance || percent > 1.0/numValues+tolerance {
t.Errorf("Value %d is outside the expected range: got %f, expected about %f", i, percent, 1.0/numValues)
}
}
}
func BenchmarkRandish(b *testing.B) {
for i := 0; i < b.N; i++ {
randish := randish.Rand()
randish.Int()
}
}