summaryrefslogtreecommitdiff
path: root/ma/ma.go
diff options
context:
space:
mode:
authorWill Hawkins <[email protected]>2021-12-10 22:14:26 -0500
committerWill Hawkins <[email protected]>2021-12-10 22:14:26 -0500
commit339a162877a78641a45338983de2192353fe7a5a (patch)
tree84ea105cd0533e0cc7c67904d78d495845d008b1 /ma/ma.go
parent5927d8aca8df26bf770ca061cdd3e00794847b27 (diff)
More work.
Diffstat (limited to 'ma/ma.go')
-rw-r--r--ma/ma.go32
1 files changed, 32 insertions, 0 deletions
diff --git a/ma/ma.go b/ma/ma.go
new file mode 100644
index 0000000..9d52d97
--- /dev/null
+++ b/ma/ma.go
@@ -0,0 +1,32 @@
+package ma
+
+import (
+ "github.com/hawkinsw/goresponsiveness/saturating"
+)
+
+// Convert this to a Type Parameterized interface when they are available
+// in Go (1.18).
+type MovingAverage struct {
+ intervals int
+ instants []uint64
+ index int
+ divisor *saturating.SaturatingInt
+}
+
+func NewMovingAverage(intervals int) *MovingAverage {
+ return &MovingAverage{instants: make([]uint64, intervals), intervals: intervals, divisor: saturating.NewSaturatingInt(intervals)}
+}
+
+func (ma *MovingAverage) AddMeasurement(measurement uint64) {
+ ma.instants[ma.index] = measurement
+ ma.divisor.Add(1)
+ ma.index = (ma.index + 1) % ma.intervals
+}
+
+func (ma *MovingAverage) CalculateAverage() float64 {
+ total := uint64(0)
+ for i := 0; i < ma.intervals; i++ {
+ total += ma.instants[i]
+ }
+ return float64(total) / float64(ma.divisor.Value())
+}