1 package metrics 2 3 import "time" 4 5 // Timer acts as a stopwatch, sending observations to a wrapped histogram. 6 // It's a bit of helpful syntax sugar for h.Observe(time.Since(x)). 7 type Timer struct { 8 h Histogram 9 t time.Time 10 u time.Duration 11 } 12 13 // NewTimer wraps the given histogram and records the current time. 14 func NewTimer(h Histogram) *Timer { 15 return &Timer{ 16 h: h, 17 t: time.Now(), 18 u: time.Second, 19 } 20 } 21 22 // ObserveDuration captures the number of seconds since the timer was 23 // constructed, and forwards that observation to the histogram. 24 func (t *Timer) ObserveDuration() { 25 d := float64(time.Since(t.t).Nanoseconds()) / float64(t.u) 26 if d < 0 { 27 d = 0 28 } 29 t.h.Observe(d) 30 } 31 32 // Unit sets the unit of the float64 emitted by the timer. 33 // By default, the timer emits seconds. 34 func (t *Timer) Unit(u time.Duration) { 35 t.u = u 36 } 37