Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set time unit on metrics.Timer #610

Merged
merged 2 commits into from
Sep 17, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
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.
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make this a proper sentence with punctuation, and provide more detail, e.g.

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
}
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) {

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove extraneous newline.

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)
}
})
}
}