-
Notifications
You must be signed in to change notification settings - Fork 0
/
ewma_test.go
95 lines (80 loc) · 1.84 KB
/
ewma_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
85
86
87
88
89
90
91
92
93
94
95
package metrics
import (
"math"
"math/rand"
"sync"
"testing"
"time"
)
func BenchmarkEWMA(b *testing.B) {
a := NewEWMA1()
b.ResetTimer()
for i := 0; i < b.N; i++ {
a.Update(1)
}
}
func BenchmarkEWMAParallel(b *testing.B) {
a := NewEWMA1()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
a.Update(1)
}
})
}
// exercise race detector.
func TestEWMAConcurrency(t *testing.T) {
a := NewEWMA1()
wg := &sync.WaitGroup{}
for i := 0; i < 100; i++ {
wg.Add(1)
go func(ewma EWMA, wg *sync.WaitGroup) {
a.Update(rand.Int63())
wg.Done()
}(a, wg)
}
wg.Wait()
}
func testEWMA(t *testing.T, alpha float64) {
r := rand.New(rand.NewSource(time.Now().Unix()))
a := NewEWMA(alpha, time.Second)
// Base case.
if rate := a.Rate(); rate != 0 {
t.Errorf("(A) Base Case a.Rate(): 0 != %v\n", rate)
}
a.Update(10)
if rate := a.Rate(); rate != 0 {
t.Errorf("(B) Base Case a.Rate(): 0 != %v\n", rate)
}
// Recursive case.
for i := 0; i < 100; i++ {
rnd := r.Int63n(1000) + 1
td, _ := NewEWMA(alpha, time.Second).(*StandardEWMA)
td.Update(10)
td.addToTimestamp(-time.Duration(rnd) * time.Second)
expect := math.Pow(1-alpha, float64(rnd-1)) * 10.00
if rate := td.Rate(); math.Abs(rate-expect) > 0.001 {
t.Errorf("(A) Recursive Case a.Rate(): %v != %v\n",
expect, rate)
}
expect = alpha*25 + (1-alpha)*expect
td.Update(25)
td.addToTimestamp(-time.Second)
if rate := td.Rate(); math.Abs(rate-expect) > 0.001 {
t.Errorf("(B) Recursive Case a.Rate(): %v != %v\n",
expect, rate)
}
}
}
func TestEWMA1(t *testing.T) {
// 1-minute moving average.
testEWMA(t, 1-math.Exp(-5.0/60.0/1))
}
func TestEWMA5(t *testing.T) {
// 5-minute moving average.
testEWMA(t, 1-math.Exp(-5.0/60.0/5))
}
func TestEWMA15(t *testing.T) {
// 15-minute moving average.
testEWMA(t, 1-math.Exp(-5.0/60.0/15))
}