-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimer.go
119 lines (89 loc) · 1.96 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
package stats
import (
"sync"
"time"
)
type TimerVector interface {
WithLabels(...string) Timer
}
type timerVector struct {
entityVector
scope Scope
name string
opts timerOptions
}
func NewTimerVector(scope Scope, name string, labels []string, opts ...TimerOption) TimerVector {
var tv = timerVector{
entityVector: entityVector{
marshaler: newDefaultMarshaler(),
labels: labels,
},
scope: scope,
name: name,
opts: defaultTimerOptions,
}
for _, opt := range opts {
opt(&tv.opts)
}
tv.newFunc = tv.newTimer
return &tv
}
func (tv *timerVector) newTimer(vs map[string]string) interface{} {
return newTimer(tv.scope.Scope("", vs), tv.name, tv.opts)
}
func (tv *timerVector) WithLabels(ls ...string) Timer {
return tv.entity(ls).(*timer)
}
type StopWatch interface {
Stop()
}
type Timer interface {
Start() StopWatch
}
type timer struct {
Histogram
p sync.Pool
}
func (t *timer) Start() StopWatch {
var sw = t.p.Get().(*stopWatch)
sw.t0 = time.Now()
return sw
}
type stopWatch struct {
t0 time.Time
timer *timer
}
type TimerOption func(*timerOptions)
type timerOptions struct {
hOpts []HistogramOption
suffix string
}
func WithHistogramOptions(hOpts ...HistogramOption) TimerOption {
return func(opts *timerOptions) {
opts.hOpts = hOpts
}
}
func WithTimerSuffix(s string) TimerOption {
return func(opts *timerOptions) {
opts.suffix = s
}
}
var defaultTimerOptions = timerOptions{
suffix: "_seconds",
}
func (sw *stopWatch) Stop() {
sw.timer.Record(time.Since(sw.t0).Seconds())
sw.timer.p.Put(sw)
}
func NewTimer(scope Scope, name string, tOpts ...TimerOption) Timer {
var opts = defaultTimerOptions
for _, opt := range tOpts {
opt(&opts)
}
return newTimer(scope, name, opts)
}
func newTimer(scope Scope, name string, opts timerOptions) *timer {
var t = timer{Histogram: scope.Histogram(name+opts.suffix, opts.hOpts...)}
t.p = sync.Pool{New: func() interface{} { return &stopWatch{timer: &t} }}
return &t
}