khenaidoo | ab1f7bd | 2019-11-14 14:00:27 -0500 | [diff] [blame^] | 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. Timer is usually used to time a function call in the |
| 27 | // following way: |
| 28 | // func TimeMe() { |
| 29 | // timer := NewTimer(myHistogram) |
| 30 | // defer timer.ObserveDuration() |
| 31 | // // Do actual work. |
| 32 | // } |
| 33 | func NewTimer(o Observer) *Timer { |
| 34 | return &Timer{ |
| 35 | begin: time.Now(), |
| 36 | observer: o, |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | // ObserveDuration records the duration passed since the Timer was created with |
| 41 | // NewTimer. It calls the Observe method of the Observer provided during |
| 42 | // construction with the duration in seconds as an argument. The observed |
| 43 | // duration is also returned. ObserveDuration is usually called with a defer |
| 44 | // statement. |
| 45 | // |
| 46 | // Note that this method is only guaranteed to never observe negative durations |
| 47 | // if used with Go1.9+. |
| 48 | func (t *Timer) ObserveDuration() time.Duration { |
| 49 | d := time.Since(t.begin) |
| 50 | if t.observer != nil { |
| 51 | t.observer.Observe(d.Seconds()) |
| 52 | } |
| 53 | return d |
| 54 | } |