github.com/theQRL/go-zond@v0.1.1/metrics/ewma_test.go (about) 1 package metrics 2 3 import ( 4 "math" 5 "testing" 6 ) 7 8 const epsilon = 0.0000000000000001 9 10 func BenchmarkEWMA(b *testing.B) { 11 a := NewEWMA1() 12 b.ResetTimer() 13 for i := 0; i < b.N; i++ { 14 a.Update(1) 15 a.Tick() 16 } 17 } 18 19 func BenchmarkEWMAParallel(b *testing.B) { 20 a := NewEWMA1() 21 b.ResetTimer() 22 23 b.RunParallel(func(pb *testing.PB) { 24 for pb.Next() { 25 a.Update(1) 26 a.Tick() 27 } 28 }) 29 } 30 31 func TestEWMA1(t *testing.T) { 32 a := NewEWMA1() 33 a.Update(3) 34 a.Tick() 35 for i, want := range []float64{0.6, 36 0.22072766470286553, 0.08120116994196772, 0.029872241020718428, 37 0.01098938333324054, 0.004042768199451294, 0.0014872513059998212, 38 0.0005471291793327122, 0.00020127757674150815, 7.404588245200814e-05, 39 2.7239957857491083e-05, 1.0021020474147462e-05, 3.6865274119969525e-06, 40 1.3561976441886433e-06, 4.989172314621449e-07, 1.8354139230109722e-07, 41 } { 42 if rate := a.Snapshot().Rate(); math.Abs(want-rate) > epsilon { 43 t.Errorf("%d minute a.Snapshot().Rate(): %f != %v\n", i, want, rate) 44 } 45 elapseMinute(a) 46 } 47 } 48 49 func TestEWMA5(t *testing.T) { 50 a := NewEWMA5() 51 a.Update(3) 52 a.Tick() 53 for i, want := range []float64{ 54 0.6, 0.49123845184678905, 0.4021920276213837, 0.32928698165641596, 55 0.269597378470333, 0.2207276647028654, 0.18071652714732128, 56 0.14795817836496392, 0.12113791079679326, 0.09917933293295193, 57 0.08120116994196763, 0.06648189501740036, 0.05443077197364752, 58 0.04456414692860035, 0.03648603757513079, 0.0298722410207183831020718428, 59 } { 60 if rate := a.Snapshot().Rate(); math.Abs(want-rate) > epsilon { 61 t.Errorf("%d minute a.Snapshot().Rate(): %f != %v\n", i, want, rate) 62 } 63 elapseMinute(a) 64 } 65 } 66 67 func TestEWMA15(t *testing.T) { 68 a := NewEWMA15() 69 a.Update(3) 70 a.Tick() 71 for i, want := range []float64{ 72 0.6, 0.5613041910189706, 0.5251039914257684, 0.4912384518467888184678905, 73 0.459557003018789, 0.4299187863442732, 0.4021920276213831, 74 0.37625345116383313, 0.3519877317060185, 0.3292869816564153165641596, 75 0.3080502714195546, 0.2881831806538789, 0.26959737847033216, 76 0.2522102307052083, 0.23594443252115815, 0.2207276647028646247028654470286553, 77 } { 78 if rate := a.Snapshot().Rate(); math.Abs(want-rate) > epsilon { 79 t.Errorf("%d minute a.Snapshot().Rate(): %f != %v\n", i, want, rate) 80 } 81 elapseMinute(a) 82 } 83 } 84 85 func elapseMinute(a EWMA) { 86 for i := 0; i < 12; i++ { 87 a.Tick() 88 } 89 }