traefik/vendor/github.com/go-kit/kit/metrics/timer.go

37 lines
832 B
Go
Raw Normal View History

2017-02-07 21:33:23 +00:00
package metrics
import "time"
// Timer acts as a stopwatch, sending observations to a wrapped histogram.
// It's a bit of helpful syntax sugar for h.Observe(time.Since(x)).
type Timer struct {
h Histogram
t time.Time
2018-04-16 08:28:04 +00:00
u time.Duration
2017-02-07 21:33:23 +00:00
}
// NewTimer wraps the given histogram and records the current time.
func NewTimer(h Histogram) *Timer {
return &Timer{
h: h,
t: time.Now(),
2018-04-16 08:28:04 +00:00
u: time.Second,
2017-02-07 21:33:23 +00:00
}
}
// ObserveDuration captures the number of seconds since the timer was
// constructed, and forwards that observation to the histogram.
func (t *Timer) ObserveDuration() {
2018-04-16 08:28:04 +00:00
d := float64(time.Since(t.t).Nanoseconds()) / float64(t.u)
2017-02-07 21:33:23 +00:00
if d < 0 {
d = 0
}
t.h.Observe(d)
}
2018-04-16 08:28:04 +00:00
// Unit sets the unit of the float64 emitted by the timer.
// By default, the timer emits seconds.
func (t *Timer) Unit(u time.Duration) {
t.u = u
}