File: avgratecounter.go

package info (click to toggle)
golang-github-paulbellamy-ratecounter 0.2.0%2Bgit20170719.a803f0e-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 108 kB
  • sloc: makefile: 3
file content (62 lines) | stat: -rw-r--r-- 1,612 bytes parent folder | download | duplicates (2)
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
package ratecounter

import (
	"strconv"
	"time"
)

// An AvgRateCounter is a thread-safe counter which returns
// the ratio between the number of calls 'Incr' and the counter value in the last interval
type AvgRateCounter struct {
	hits     *RateCounter
	counter  *RateCounter
	interval time.Duration
}

// NewAvgRateCounter constructs a new AvgRateCounter, for the interval provided
func NewAvgRateCounter(intrvl time.Duration) *AvgRateCounter {
	return &AvgRateCounter{
		hits:     NewRateCounter(intrvl),
		counter:  NewRateCounter(intrvl),
		interval: intrvl,
	}
}

// WithResolution determines the minimum resolution of this counter
func (a *AvgRateCounter) WithResolution(resolution int) *AvgRateCounter {
	if resolution < 1 {
		panic("AvgRateCounter resolution cannot be less than 1")
	}

	a.hits = a.hits.WithResolution(resolution)
	a.counter = a.counter.WithResolution(resolution)

	return a
}

// Incr Adds an event into the AvgRateCounter
func (a *AvgRateCounter) Incr(val int64) {
	a.hits.Incr(1)
	a.counter.Incr(val)
}

// Rate Returns the current ratio between the events count and its values during the last interval
func (a *AvgRateCounter) Rate() float64 {
	hits, value := a.hits.Rate(), a.counter.Rate()

	if hits == 0 {
		return 0 // Avoid division by zero
	}

	return float64(value) / float64(hits)
}

// Hits returns the number of calling method Incr during specified interval
func (a *AvgRateCounter) Hits() int64 {
	return a.hits.Rate()
}

// String returns counter's rate formatted to string
func (a *AvgRateCounter) String() string {
	return strconv.FormatFloat(a.Rate(), 'e', 5, 64)
}