Merge pull request #610 from esenac/timer-unit
Set time unit on metrics.Timer
Peter Bourgon authored 6 years ago
GitHub committed 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 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 | } |
30 | 30 | t.Errorf("want %.3f, have %.3f", want, have) |
31 | 31 | } |
32 | 32 | } |
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 | } |