Debian Codegraph @

prometheus/timer.go

raw
1 // Copyright 2016 The Prometheus Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package prometheus
15
16 import "time"
17
18 // Timer is a helper type to time functions. Use NewTimer to create new
19 // instances.
20 type Timer struct {
21 begin time.Time
22 observer Observer
23 }
24
25 // NewTimer creates a new Timer. The provided Observer is used to observe a
26 // duration in seconds. If the Observer implements ExemplarObserver, passing exemplar
27 // later on will be also supported.
28 // Timer is usually used to time a function call in the
29 // following way:
30 //
31 // func TimeMe() {
32 // timer := NewTimer(myHistogram)
33 // defer timer.ObserveDuration()
34 // // Do actual work.
35 // }
36 //
37 // or
38 //
39 // func TimeMeWithExemplar() {
40 // timer := NewTimer(myHistogram)
41 // defer timer.ObserveDurationWithExemplar(exemplar)
42 // // Do actual work.
43 // }
44 func NewTimer(o Observer) *Timer {
45 return &Timer{
46 begin: time.Now(),
47 observer: o,
48 }
49 }
50
51 // ObserveDuration records the duration passed since the Timer was created with
52 // NewTimer. It calls the Observe method of the Observer provided during
53 // construction with the duration in seconds as an argument. The observed
54 // duration is also returned. ObserveDuration is usually called with a defer
55 // statement.
56 //
57 // Note that this method is only guaranteed to never observe negative durations
58 // if used with Go1.9+.
59 func (t *Timer) ObserveDuration() time.Duration {
60 d := time.Since(t.begin)
61 if t.observer != nil {
62 t.observer.Observe(d.Seconds())
63 }
64 return d
65 }
66
67 // ObserveDurationWithExemplar is like ObserveDuration, but it will also
68 // observe exemplar with the duration unless exemplar is nil or provided Observer can't
69 // be casted to ExemplarObserver.
70 func (t *Timer) ObserveDurationWithExemplar(exemplar Labels) time.Duration {
71 d := time.Since(t.begin)
72 eo, ok := t.observer.(ExemplarObserver)
73 if ok && exemplar != nil {
74 eo.ObserveWithExemplar(d.Seconds(), exemplar)
75 return d
76 }
77 if t.observer != nil {
78 t.observer.Observe(d.Seconds())
79 }
80 return d
81 }