diff --git a/metrics/debug.test b/metrics/debug.test new file mode 100755 index 0000000..f9a180b Binary files /dev/null and b/metrics/debug.test differ diff --git a/metrics/timer.go b/metrics/timer.go index c354df0..52aa5ae 100644 --- a/metrics/timer.go +++ b/metrics/timer.go @@ -7,6 +7,7 @@ type Timer struct { h Histogram t time.Time + u time.Duration } // NewTimer wraps the given histogram and records the current time. @@ -14,15 +15,21 @@ return &Timer{ h: h, t: time.Now(), + u: time.Second, } } // ObserveDuration captures the number of seconds since the timer was // constructed, and forwards that observation to the histogram. func (t *Timer) ObserveDuration() { - d := time.Since(t.t).Seconds() + d := float64(time.Since(t.t).Nanoseconds()) / float64(t.u) if d < 0 { d = 0 } t.h.Observe(d) } + +// Unit sets the timer time unit +func (t *Timer) Unit(u time.Duration) { + t.u = u +} diff --git a/metrics/timer_test.go b/metrics/timer_test.go index dedab2a..1e08408 100644 --- a/metrics/timer_test.go +++ b/metrics/timer_test.go @@ -31,3 +31,29 @@ t.Errorf("want %.3f, have %.3f", want, have) } } + +func TestTimerUnit(t *testing.T) { + + for _, tc := range []struct { + name string + unit time.Duration + tolerance float64 + want float64 + }{ + {"Seconds", time.Second, 0.010, 0.100}, + {"Milliseconds", time.Millisecond, 10, 100}, + {"Nanoseconds", time.Nanosecond, 10000000, 100000000}, + } { + t.Run(tc.name, func(t *testing.T) { + h := generic.NewSimpleHistogram() + timer := metrics.NewTimer(h) + time.Sleep(100 * time.Millisecond) + timer.Unit(tc.unit) + timer.ObserveDuration() + + if want, have := tc.want, h.ApproximateMovingAverage(); math.Abs(want-have) > tc.tolerance { + t.Errorf("want %.3f, have %.3f", want, have) + } + }) + } +}