Set time unit on metrics.Timer
esenac
6 years ago
Binary diff not shown
6 | 6 | type Timer struct { |
7 | 7 | h Histogram |
8 | 8 | t time.Time |
9 | u time.Duration | |
9 | 10 | } |
10 | 11 | |
11 | 12 | // NewTimer wraps the given histogram and records the current time. |
13 | 14 | return &Timer{ |
14 | 15 | h: h, |
15 | 16 | t: time.Now(), |
17 | u: time.Second, | |
16 | 18 | } |
17 | 19 | } |
18 | 20 | |
19 | 21 | // ObserveDuration captures the number of seconds since the timer was |
20 | 22 | // constructed, and forwards that observation to the histogram. |
21 | 23 | func (t *Timer) ObserveDuration() { |
22 | d := time.Since(t.t).Seconds() | |
24 | d := float64(time.Since(t.t).Nanoseconds()) / float64(t.u) | |
23 | 25 | if d < 0 { |
24 | 26 | d = 0 |
25 | 27 | } |
26 | 28 | t.h.Observe(d) |
27 | 29 | } |
30 | ||
31 | // Unit sets the timer time unit | |
32 | func (t *Timer) Unit(u time.Duration) { | |
33 | t.u = u | |
34 | } |
30 | 30 | t.Errorf("want %.3f, have %.3f", want, have) |
31 | 31 | } |
32 | 32 | } |
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 | } |