Debian Codegraph @

ratelimit_bench_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 package ratelimit
2
3 import (
4 "fmt"
5 "runtime"
6 "sync"
7 "testing"
8
9 "go.uber.org/atomic"
10 )
11
12 func BenchmarkRateLimiter(b *testing.B) {
13 count := atomic.NewInt64(0)
14 for _, procs := range []int{1, 4, 8, 16} {
15 runtime.GOMAXPROCS(procs)
16 for name, limiter := range map[string]Limiter{
17 "atomic": newAtomicBased(b.N * 1000000000000),
18 "atomic_int64": newAtomicInt64Based(b.N * 1000000000000),
19 "mutex": newMutexBased(b.N * 1000000000000),
20 } {
21 for ng := 1; ng < 16; ng++ {
22 runner(b, name, procs, ng, limiter, count)
23 }
24 for ng := 16; ng < 128; ng += 8 {
25 runner(b, name, procs, ng, limiter, count)
26 }
27 for ng := 128; ng < 512; ng += 16 {
28 runner(b, name, procs, ng, limiter, count)
29 }
30 for ng := 512; ng < 1024; ng += 32 {
31 runner(b, name, procs, ng, limiter, count)
32 }
33 for ng := 1024; ng < 2048; ng += 64 {
34 runner(b, name, procs, ng, limiter, count)
35 }
36 for ng := 2048; ng < 4096; ng += 128 {
37 runner(b, name, procs, ng, limiter, count)
38 }
39 for ng := 4096; ng < 16384; ng += 512 {
40 runner(b, name, procs, ng, limiter, count)
41 }
42 for ng := 16384; ng < 65536; ng += 2048 {
43 runner(b, name, procs, ng, limiter, count)
44 }
45 }
46 }
47 fmt.Printf("\nmark%d\n", count.Load())
48 }
49
50 func runner(b *testing.B, name string, procs int, ng int, limiter Limiter, count *atomic.Int64) bool {
51 return b.Run(fmt.Sprintf("type:%s;max_procs:%d;goroutines:%d", name, procs, ng), func(b *testing.B) {
52 b.ReportAllocs()
53
54 var wg sync.WaitGroup
55 trigger := atomic.NewBool(true)
56 n := b.N
57 batchSize := n / ng
58 if batchSize == 0 {
59 batchSize = n
60 }
61 for n > 0 {
62 wg.Add(1)
63 batch := min(n, batchSize)
64 n -= batch
65 go func(quota int) {
66 for trigger.Load() {
67 runtime.Gosched()
68 }
69 localCnt := 0
70 for i := 0; i < quota; i++ {
71 res := limiter.Take()
72 localCnt += res.Nanosecond()
73 }
74 count.Add(int64(localCnt))
75 wg.Done()
76 }(batch)
77 }
78
79 b.StartTimer()
80 trigger.Store(false)
81 wg.Wait()
82 b.StopTimer()
83 })
84 }
85
86 func min(a, b int) int {
87 if a < b {
88 return a
89 }
90 return b
91 }