Skip to content

Commit

Permalink
Set time unit on metrics.Timer
Browse files Browse the repository at this point in the history
  • Loading branch information
esenac committed Sep 15, 2017
1 parent f7593d1 commit 4e222a3
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
Binary file added metrics/debug.test
Binary file not shown.
9 changes: 8 additions & 1 deletion metrics/timer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,29 @@ import "time"
type Timer struct {
h Histogram
t time.Time
u time.Duration
}

// NewTimer wraps the given histogram and records the current time.
func NewTimer(h Histogram) *Timer {
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
}
26 changes: 26 additions & 0 deletions metrics/timer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,29 @@ func TestTimerSlow(t *testing.T) {
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)
}
})
}
}

0 comments on commit 4e222a3

Please sign in to comment.