avgovertime.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package aggregator
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. // averageOverTimeAggregator is a MetricAggregator which returns the average of values it is aggregating by dividing the
  7. // total of all values by the count of unique timestamps
  8. type averageOverTimeAggregator struct {
  9. lock sync.Mutex
  10. labelValues []string
  11. total float64
  12. count int
  13. currentTime *time.Time
  14. }
  15. func AverageOverTime(labelValues []string) MetricAggregator {
  16. return &averageOverTimeAggregator{
  17. labelValues: labelValues,
  18. }
  19. }
  20. func (a *averageOverTimeAggregator) AdditionInfo() map[string]string {
  21. return nil
  22. }
  23. func (a *averageOverTimeAggregator) LabelValues() []string {
  24. return a.labelValues
  25. }
  26. func (a *averageOverTimeAggregator) Update(value float64, timestamp time.Time, additionalInfo map[string]string) {
  27. a.lock.Lock()
  28. defer a.lock.Unlock()
  29. a.total += value
  30. if a.currentTime == nil || !timestamp.Equal(*a.currentTime) {
  31. a.currentTime = &timestamp
  32. a.count++
  33. }
  34. }
  35. func (a *averageOverTimeAggregator) Value() []MetricValue {
  36. a.lock.Lock()
  37. defer a.lock.Unlock()
  38. if a.count == 0 {
  39. return []MetricValue{
  40. {
  41. Value: 0,
  42. },
  43. }
  44. }
  45. return []MetricValue{
  46. {a.total / float64(a.count), nil},
  47. }
  48. }