Codebase list golang-github-go-kit-kit / 4e222a3
Set time unit on metrics.Timer esenac 6 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 timer time unit
32 func (t *Timer) Unit(u time.Duration) {
33 t.u = u
34 }
3030 t.Errorf("want %.3f, have %.3f", want, have)
3131 }
3232 }
33
34 func TestTimerUnit(t *testing.T) {
35
36 for _, tc := range []struct {
37 name string
38 unit time.Duration
39 tolerance float64
40 want float64
41 }{
42 {"Seconds", time.Second, 0.010, 0.100},
43 {"Milliseconds", time.Millisecond, 10, 100},
44 {"Nanoseconds", time.Nanosecond, 10000000, 100000000},
45 } {
46 t.Run(tc.name, func(t *testing.T) {
47 h := generic.NewSimpleHistogram()
48 timer := metrics.NewTimer(h)
49 time.Sleep(100 * time.Millisecond)
50 timer.Unit(tc.unit)
51 timer.ObserveDuration()
52
53 if want, have := tc.want, h.ApproximateMovingAverage(); math.Abs(want-have) > tc.tolerance {
54 t.Errorf("want %.3f, have %.3f", want, have)
55 }
56 })
57 }
58 }