forked from libp2p/go-flow-metrics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
meter_test.go
73 lines (56 loc) · 1.27 KB
/
meter_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package flow
import (
"fmt"
"math"
"sync"
"testing"
"time"
)
func ExampleMeter() {
meter := new(Meter)
t := time.NewTicker(100 * time.Millisecond)
for i := 0; i < 100; i++ {
<-t.C
meter.Mark(30)
}
// Get the current rate. This will be accurate *now* but not after we
// sleep (because we calculate it using EWMA).
rate := meter.Snapshot().Rate
// Sleep 2 seconds to allow the total to catch up. We snapshot every
// second so the total may not yet be accurate.
time.Sleep(2 * time.Second)
// Get the current total.
total := meter.Snapshot().Total
fmt.Printf("%d (%d/s)\n", total, roundTens(rate))
// Output: 3000 (300/s)
}
func TestResetMeter(t *testing.T) {
meter := new(Meter)
meter.Mark(30)
time.Sleep(2 * time.Second)
if total := meter.Snapshot().Total; total != 30 {
t.Errorf("total = %d; want 30", total)
}
meter.Reset()
if total := meter.Snapshot().Total; total != 0 {
t.Errorf("total = %d; want 0", total)
}
}
func TestMarkResetMeterMulti(t *testing.T) {
var wg sync.WaitGroup
wg.Add(2)
meter := new(Meter)
go func(meter *Meter) {
meter.Mark(30)
meter.Mark(30)
wg.Done()
}(meter)
go func(meter *Meter) {
meter.Reset()
wg.Done()
}(meter)
wg.Wait()
}
func roundTens(x float64) int64 {
return int64(math.Floor(x/10+0.5)) * 10
}