Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added metrics/debug.test
Binary file not shown.
10 changes: 9 additions & 1 deletion metrics/timer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,30 @@ 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 unit of the float64 emitted by the timer.
// By default, the timer emits seconds.
func (t *Timer) Unit(u time.Duration) {
t.u = u
}
25 changes: 25 additions & 0 deletions metrics/timer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,28 @@ 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)
}
})
}
}