forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
221 lines (192 loc) · 4.05 KB
/
timer.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package timer
import (
"math/rand"
"sync"
"time"
)
type Timer interface {
// Start the timer
// Timer must be stopped, which is the state of a new timer.
Start()
// Pause the timer.
// Timer must be started.
Pause()
// Resumed the timer.
// Timer must be paused.
Resume()
// Stop the timer.
// Timer must be started.
Stop()
}
type timerState int
// A variable that is settable.
// The use of this interface allows for control
// on how the averaged timed value accessed.
type Setter interface {
Set(int64)
}
const (
Stopped timerState = iota
Started
Paused
)
// Perform basic timings of sections of code.
// Keeps a running average of timing values.
type timer struct {
sampleRate float64
i int64
start time.Time
current time.Duration
avg *movavg
state timerState
avgVar Setter
random *rand.Rand
}
func New(sampleRate float64, movingAverageSize int, avgVar Setter) Timer {
return &timer{
sampleRate: sampleRate,
avg: newMovAvg(movingAverageSize),
avgVar: avgVar,
// Each timer gets its own random source or else
// all timers would be locking on the global source.
random: rand.New(rand.NewSource(rand.Int63())),
}
}
// Start timer.
func (t *timer) Start() {
if t.state != Stopped {
panic("invalid timer state")
}
if t.random.Float64() < t.sampleRate {
t.state = Started
t.start = time.Now()
}
}
// Pause current timing event.
func (t *timer) Pause() {
if t.state != Started {
return
}
t.current += time.Now().Sub(t.start)
t.state = Paused
}
// Resumed paused timer.
func (t *timer) Resume() {
if t.state != Paused {
return
}
t.start = time.Now()
t.state = Started
}
// Stop and record time of event.
// The moving average is updated at this point.
func (t *timer) Stop() {
if t.state != Started {
return
}
t.current += time.Now().Sub(t.start)
// Use float64 precision when performing movavg calculations.
avg := t.avg.update(float64(t.current))
t.current = 0
t.state = Stopped
// Truncate to int64 now that we have a final value.
t.avgVar.Set(int64(avg))
}
// Maintains a moving average of values
type movavg struct {
size int
history []float64
idx int
count int
avg float64
}
func newMovAvg(size int) *movavg {
return &movavg{
size: size,
history: make([]float64, size),
idx: -1,
}
}
func (m *movavg) update(value float64) float64 {
m.count++
n := float64(m.count)
m.avg += (value - m.avg) / n
m.idx = (m.idx + 1) % m.size
if m.count == m.size+1 {
old := m.history[m.idx]
m.avg = (n*m.avg - old) / (n - 1)
m.count--
}
m.history[m.idx] = value
return m.avg
}
// A setter that can have distinct part or sections.
// By using a MultiPartSetter one can time distinct sections
// of code and have their individuals times summed
// to form a total timed value.
type MultiPartSetter struct {
mu sync.Mutex
wg sync.WaitGroup
stopping chan struct{}
setter Setter
partValues []int64
updates chan update
}
func NewMultiPartSetter(setter Setter) *MultiPartSetter {
mp := &MultiPartSetter{
setter: setter,
updates: make(chan update),
stopping: make(chan struct{}),
}
mp.wg.Add(1)
go mp.run()
return mp
}
// Add a new distinct part. As new timings are set
// for this part they will contribute to the total time.
func (mp *MultiPartSetter) NewPart() Setter {
mp.mu.Lock()
defer mp.mu.Unlock()
p := part{
id: len(mp.partValues),
updates: mp.updates,
stopping: mp.stopping,
}
mp.partValues = append(mp.partValues, 0)
return p
}
func (mp *MultiPartSetter) Stop() {
close(mp.stopping)
mp.wg.Wait()
}
func (mp *MultiPartSetter) run() {
defer mp.wg.Done()
for {
select {
case <-mp.stopping:
return
case update := <-mp.updates:
mp.partValues[update.part] = update.value
var sum int64
for _, v := range mp.partValues {
sum += v
}
mp.setter.Set(sum)
}
}
}
type update struct {
part int
value int64
}
type part struct {
id int
updates chan<- update
stopping chan struct{}
}
func (p part) Set(v int64) {
select {
case <-p.stopping:
case p.updates <- update{part: p.id, value: v}:
}
}