1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package distribution
16
17 import (
18 "sync"
19 "testing"
20 )
21
22 func TestDistribution(t *testing.T) {
23
24 tests := []struct {
25
26 vals []int
27
28
29 pp []float64
30 vv []int
31 }{
32 {
33 vals: []int{15, 20, 35, 40, 50},
34 pp: []float64{0.05, 0.3, 0.4, 0.5, 1},
35 vv: []int{15, 20, 20, 35, 50},
36 },
37 {
38 vals: []int{3, 6, 7, 8, 8, 10, 13, 15, 16, 20},
39 pp: []float64{0.25, 0.5, 0.75, 1},
40 vv: []int{7, 8, 15, 20},
41 },
42 {
43 vals: []int{3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20},
44 pp: []float64{0.25, 0.5, 0.75, 1},
45 vv: []int{7, 9, 15, 20},
46 },
47 }
48
49 maxVal := 0
50 for _, tst := range tests {
51 for _, v := range tst.vals {
52 if maxVal < v {
53 maxVal = v
54 }
55 }
56 }
57
58 for _, tst := range tests {
59 d := New(maxVal + 1)
60 for _, v := range tst.vals {
61 d.Record(v)
62 }
63 for i, p := range tst.pp {
64 got, want := d.Percentile(p), tst.vv[i]
65 if got != want {
66 t.Errorf("d=%v, d.Percentile(%f)=%d, want %d", d, p, got, want)
67 }
68 }
69 }
70 }
71
72 func TestRace(t *testing.T) {
73 const N int = 1e3
74 const parallel = 2
75
76 d := New(N)
77
78 var wg sync.WaitGroup
79 wg.Add(parallel)
80 for i := 0; i < parallel; i++ {
81 go func() {
82 for i := 0; i < N; i++ {
83 d.Record(i)
84 }
85 wg.Done()
86 }()
87 }
88
89 for i := 0; i < N; i++ {
90 if p := d.Percentile(0.5); p > N {
91 t.Fatalf("d.Percentile(0.5)=%d, expected to be at most %d", p, N)
92 }
93 }
94 }
95
96 func BenchmarkDistribution(b *testing.B) {
97 const N int = 1e3
98
99 d := New(N)
100 for i := 0; i < N; i++ {
101 d.Record(i)
102 }
103
104 b.ResetTimer()
105 b.ReportAllocs()
106
107 var index int
108 for i := 0; i < b.N; i++ {
109 if index = d.Percentile(0.5); index < 0 {
110 b.Fatalf("Invalid index: %d", index)
111 }
112 }
113 if index == 0 {
114 b.Fatal("Benchmark did not run")
115 }
116 }
117
View as plain text