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
6 // http://www.apache.org/licenses/LICENSE-2.0
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.
18 // Timer is a helper type to time functions. Use NewTimer to create new
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
29 // timer := NewTimer(myHistogram)
30 // defer timer.ObserveDuration()
33 func NewTimer(o Observer) *Timer {
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
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())