-
Notifications
You must be signed in to change notification settings - Fork 14
/
counter.go
54 lines (42 loc) · 856 Bytes
/
counter.go
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
package iocontrol
import (
"sync"
"time"
"github.com/benbjohnson/clock"
)
type rateCounter struct {
time clock.Clock // YAGNI, maybe, idk, how to test this
mu sync.RWMutex
count int
lastCount int
lastCheck time.Time
}
func newCounter() *rateCounter {
return &rateCounter{
time: clock.New(),
}
}
func (c *rateCounter) Add(n int) {
c.mu.Lock()
defer c.mu.Unlock()
c.count += n
if c.lastCheck.IsZero() {
c.lastCheck = time.Now()
}
}
func (c *rateCounter) Total() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.count
}
func (c *rateCounter) Rate(perPeriod time.Duration) float64 {
c.mu.Lock()
defer c.mu.Unlock()
now := c.time.Now()
between := now.Sub(c.lastCheck)
changed := c.count - c.lastCount
rate := float64(changed*int(perPeriod)) / float64(between)
c.lastCount = c.count
c.lastCheck = now
return rate
}