github.com/haraldrudell/parl@v0.4.176/ptime/average-interval.go (about) 1 /* 2 © 2023–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package ptime 7 8 import ( 9 "sync" 10 ) 11 12 // AverageInterval is a container for the datapoint aggregate over a single period 13 type AverageInterval struct { 14 index PeriodIndex 15 16 totalLock sync.RWMutex 17 count uint64 18 total float64 19 } 20 21 // NewAverageInterval returns an avareging container for one averaging interval 22 func NewAverageInterval(index PeriodIndex) (ai *AverageInterval) { 23 return &AverageInterval{index: index} 24 } 25 26 func (a *AverageInterval) Index() (index PeriodIndex) { 27 return a.index 28 } 29 30 // Add adds a datapoint to the averager 31 // - count of values incremented 32 // - value added to total 33 func (a *AverageInterval) Add(value float64) { 34 a.totalLock.Lock() 35 defer a.totalLock.Unlock() 36 37 a.count++ 38 a.total += value 39 } 40 41 // Aggregate provides averaging content for calculating the average 42 func (a *AverageInterval) Aggregate(countp *uint64, floatp *float64) { 43 a.totalLock.RLock() 44 defer a.totalLock.RUnlock() 45 46 *countp += a.count 47 *floatp += a.total 48 }