-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.go
83 lines (67 loc) · 1.29 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
package god
import (
"fmt"
"sync"
"time"
)
// Timer is a simple operations timer.
type Timer struct {
list []time.Duration
mutex sync.Mutex
}
// NewTimer will create and return a timer.
func NewTimer(name string) *Timer {
t := &Timer{}
Register(name, t)
return t
}
// Add will add the duration to the timer.
func (t *Timer) Add(d time.Duration) {
t.mutex.Lock()
t.list = append(t.list, d)
t.mutex.Unlock()
}
// Measure can be used to track a function using defer.
func (t *Timer) Measure() func() {
now := time.Now()
return func() {
t.Add(time.Since(now))
}
}
// Collect implements the Metric interface.
func (t *Timer) Collect() string {
// lock mutex
t.mutex.Lock()
// prepare mean
var min time.Duration
var mean time.Duration
var max time.Duration
// get mean
if len(t.list) > 0 {
// set min and max
min = t.list[0]
max = t.list[0]
// prepare sum
var sum time.Duration
// iterate through all values
for _, i := range t.list {
// add up
sum += i
// check min
if i < min {
min = i
}
// check max
if i > max {
max = i
}
}
// calculate mean
mean = sum / time.Duration(len(t.list))
}
// reset list
t.list = nil
// unlock mutex
t.mutex.Unlock()
return fmt.Sprintf("%s/%s/%s", min.String(), mean.String(), max.String())
}