-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrateLimiter_test.go
77 lines (73 loc) · 1.56 KB
/
rateLimiter_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
package golangUtil
import (
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestSlideWindows(t *testing.T) {
println(TryAcquire())
}
func BenchmarkTryAcquire(b *testing.B) {
group := sync.WaitGroup{}
group.Add(b.N)
timeGap := time.Microsecond * 10000
rate := getRateLimiterMiddleware(WithWindowsSize(timeGap), WithSubWindowsNumber(10000), WithMaxPassingPerWindows(1024))
var totalResult int64
go func() {
tick := time.Tick(timeGap)
for {
select {
case <-tick:
if totalResult > rate.permitsPerWindows {
fmt.Println(totalResult)
}
atomic.SwapInt64(&totalResult, 0)
//tick = time.After(timeGap)
}
}
}()
for i := 0; i < b.N; i++ {
go func() {
defer group.Done()
result := rate.TryAcquire()
if result {
atomic.AddInt64(&totalResult, 1)
}
}()
}
group.Wait()
}
func TestConcurrencyTryAcquire(t *testing.T) {
const times = 10000
group := sync.WaitGroup{}
group.Add(times)
var smoothTimes time.Duration = 30 * time.Millisecond
var resultInt int64
var cycle int64 = 0
for i := 0; i < times; i++ {
go func() {
defer group.Done()
time.Sleep(smoothTimes)
if cycle >= 100 && smoothTimes < 3*time.Second {
smoothTimes += smoothTimes * 10
cycle = 0
} else {
atomic.AddInt64(&cycle, 1)
}
result := TryAcquire()
if slideLimiter.totalCount > slideLimiter.permitsPerWindows {
panic(any("slide windows invalid"))
}
if result {
atomic.AddInt64(&resultInt, 1)
}
}()
}
group.Wait()
println(resultInt)
for key, value := range slideLimiter.windows {
println(key, ":", value)
}
}