forked from Laisky/go-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththrottle_test.go
101 lines (88 loc) · 1.85 KB
/
throttle_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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package utils
import (
"context"
"fmt"
"testing"
"time"
"golang.org/x/time/rate"
)
// FIXME: sometime failed
func TestThrottle2(t *testing.T) {
ctx := context.Background()
throttle, err := NewThrottleWithCtx(ctx, &ThrottleCfg{
NPerSec: 10,
Max: 100,
})
if err != nil {
t.Fatalf("%+v", err)
}
defer throttle.Close()
time.Sleep(100 * time.Millisecond)
for i := 0; i < 20; i++ {
if !throttle.Allow() {
if i < 10 {
t.Fatalf("should be allowed: %v", i)
} else {
break
}
}
}
time.Sleep(2050 * time.Millisecond)
for i := 0; i < 20; i++ {
if !throttle.Allow() {
t.Fatalf("should be allowed: %v", i)
}
}
for i := 0; i < 100; i++ {
if throttle.Allow() {
t.Errorf("should not be allowed: %v", i)
}
}
}
// BenchmarkThrottle/throttle-8 13897974 85.3 ns/op 0 B/op 0 allocs/op
// BenchmarkThrottle/rate.Limiter-8 148858 7344 ns/op 0 B/op 0 allocs/op
func BenchmarkThrottle(b *testing.B) {
ctx := context.Background()
b.Run("throttle", func(b *testing.B) {
throttle, err := NewThrottleWithCtx(ctx, &ThrottleCfg{
NPerSec: 10,
Max: 100,
})
if err != nil {
b.Fatalf("%+v", err)
}
defer throttle.Close()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
throttle.Allow()
}
})
})
b.Run("rate.Limiter", func(b *testing.B) {
limiter := rate.NewLimiter(rate.Limit(10), 100)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
limiter.Allow()
}
})
})
}
func ExampleThrottle() {
ctx := context.Background()
throttle, err := NewThrottleWithCtx(ctx, &ThrottleCfg{
NPerSec: 10,
Max: 100,
})
if err != nil {
Logger.Panic("new throttle")
}
defer throttle.Close()
inChan := make(chan int)
for msg := range inChan {
if !throttle.Allow() {
continue
}
// do something with msg
fmt.Println(msg)
}
}