Package list golang-github-go-kit-kit / b5c889e
Merge pull request #610 from esenac/timer-unit Set time unit on metrics.Timer Peter Bourgon authored 4 years ago GitHub committed 4 years ago
3 changed file(s) with 34 addition(s) and 1 deletion(s). Raw diff Collapse all Expand all
Binary diff not shown
66 type Timer struct {
77 h Histogram
88 t time.Time
9 u time.Duration
910 }
1011
1112 // NewTimer wraps the given histogram and records the current time.
1314 return &Timer{
1415 h: h,
1516 t: time.Now(),
17 u: time.Second,
1618 }
1719 }
1820
1921 // ObserveDuration captures the number of seconds since the timer was
2022 // constructed, and forwards that observation to the histogram.
2123 func (t *Timer) ObserveDuration() {
22 d := time.Since(t.t).Seconds()
24 d := float64(time.Since(t.t).Nanoseconds()) / float64(t.u)
2325 if d < 0 {
2426 d = 0
2527 }
2628 t.h.Observe(d)
2729 }
30
31 // Unit sets the unit of the float64 emitted by the timer.
32 // By default, the timer emits seconds.
33 func (t *Timer) Unit(u time.Duration) {
34 t.u = u
35 }
3030 t.Errorf("want %.3f, have %.3f", want, have)
3131 }
3232 }
33
34 func TestTimerUnit(t *testing.T) {
35 for _, tc := range []struct {
36 name string
37 unit time.Duration
38 tolerance float64
39 want float64
40 }{
41 {"Seconds", time.Second, 0.010, 0.100},
42 {"Milliseconds", time.Millisecond, 10, 100},
43 {"Nanoseconds", time.Nanosecond, 10000000, 100000000},
44 } {
45 t.Run(tc.name, func(t *testing.T) {
46 h := generic.NewSimpleHistogram()
47 timer := metrics.NewTimer(h)
48 time.Sleep(100 * time.Millisecond)
49 timer.Unit(tc.unit)
50 timer.ObserveDuration()
51
52 if want, have := tc.want, h.ApproximateMovingAverage(); math.Abs(want-have) > tc.tolerance {
53 t.Errorf("want %.3f, have %.3f", want, have)
54 }
55 })
56 }
57 }