Codebase list golang-github-go-kit-kit / ca10969
Merge pull request #358 from go-kit/metrics-timer metrics: add Timer Peter Bourgon authored 7 years ago GitHub committed 7 years ago
2 changed file(s) with 61 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 package metrics
1
2 import "time"
3
4 // Timer acts as a stopwatch, sending observations to a wrapped histogram.
5 // It's a bit of helpful syntax sugar for h.Observe(time.Since(x)).
6 type Timer struct {
7 h Histogram
8 t time.Time
9 }
10
11 // NewTimer wraps the given histogram and records the current time.
12 func NewTimer(h Histogram) *Timer {
13 return &Timer{
14 h: h,
15 t: time.Now(),
16 }
17 }
18
19 // ObserveDuration captures the number of seconds since the timer was
20 // constructed, and forwards that observation to the histogram.
21 func (t *Timer) ObserveDuration() {
22 d := time.Since(t.t).Seconds()
23 if d < 0 {
24 d = 0
25 }
26 t.h.Observe(d)
27 }
0 package metrics_test
1
2 import (
3 "math"
4 "testing"
5
6 "time"
7
8 "github.com/go-kit/kit/metrics"
9 "github.com/go-kit/kit/metrics/generic"
10 )
11
12 func TestTimerFast(t *testing.T) {
13 h := generic.NewSimpleHistogram()
14 metrics.NewTimer(h).ObserveDuration()
15
16 tolerance := 0.050
17 if want, have := 0.000, h.ApproximateMovingAverage(); math.Abs(want-have) > tolerance {
18 t.Errorf("want %.3f, have %.3f", want, have)
19 }
20 }
21
22 func TestTimerSlow(t *testing.T) {
23 h := generic.NewSimpleHistogram()
24 timer := metrics.NewTimer(h)
25 time.Sleep(250 * time.Millisecond)
26 timer.ObserveDuration()
27
28 tolerance := 0.050
29 if want, have := 0.250, h.ApproximateMovingAverage(); math.Abs(want-have) > tolerance {
30 t.Errorf("want %.3f, have %.3f", want, have)
31 }
32 }