-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcounter.go
42 lines (33 loc) · 822 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
package gostats
import (
"sync"
"time"
)
type counter struct {
LastUpdate time.Time
LastValue int64
}
var counterTracker = make(map[string]counter)
var trackerMutex = &sync.Mutex{}
func perSecondCounter(name string, value int64) float64 {
trackerMutex.Lock()
defer trackerMutex.Unlock()
updateTime := time.Now()
var tracker counter
tracker, found := counterTracker[name]
if !found {
tracker.LastUpdate = updateTime
tracker.LastValue = value
counterTracker[name] = tracker
}
secondsSince := updateTime.Sub(tracker.LastUpdate).Seconds()
valueDiff := value - tracker.LastValue
tracker.LastUpdate = updateTime
tracker.LastValue = value
counterTracker[name] = tracker
if secondsSince == 0 {
return float64(0)
}
changePerSecond := float64(valueDiff) / secondsSince
return changePerSecond
}