-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathloader_bench_test.go
More file actions
91 lines (83 loc) · 1.98 KB
/
loader_bench_test.go
File metadata and controls
91 lines (83 loc) · 1.98 KB
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
package crema
import (
"context"
"fmt"
"sync/atomic"
"testing"
"time"
)
func BenchmarkLoader(b *testing.B) {
benchCases := []struct {
name string
newLoader func() internalLoader[int]
}{
{
name: "singleflight",
newLoader: func() internalLoader[int] {
return newSingleflightLoader[int](NoopMetricsProvider{}, 0)
},
},
{
name: "direct",
newLoader: func() internalLoader[int] {
return directLoader[int]{}
},
},
}
collisionRates := []int{0, 90}
sleepDurations := []time.Duration{0, 1 * time.Millisecond}
parallelisms := []int{1, 100}
for _, sleepDuration := range sleepDurations {
for _, bc := range benchCases {
for _, collision := range collisionRates {
for _, parallelism := range parallelisms {
b.Run(fmt.Sprintf("%s/sleep_%s/collision_%d/parallel_%d", bc.name, sleepDuration, collision, parallelism), func(b *testing.B) {
loader := bc.newLoader()
b.ReportAllocs()
var counter uint64
ctx := context.Background()
b.SetParallelism(parallelism)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
idx := atomic.AddUint64(&counter, 1) - 1
key := selectKey(idx, collision)
loadFunc := func(ctx context.Context) (int, error) {
if sleepDuration > 0 {
time.Sleep(sleepDuration)
}
return len(key), nil
}
if _, _, err := loader.load(ctx, key, loadFunc); err != nil {
b.Fatal(err)
}
}
})
})
}
}
}
}
}
func selectKey(idx uint64, collisionPercent int) string {
if idx%100 < uint64(collisionPercent) {
return keyFor(0)
}
return keyFor(idx)
}
func keyFor(idx uint64) string {
const prefix = "key-"
const digits = 20
var buf [len(prefix) + digits]byte
copy(buf[:len(prefix)], prefix)
for i := len(prefix); i < len(buf); i++ {
buf[i] = '0'
}
for i := len(buf) - 1; i >= len(prefix); i-- {
buf[i] = byte('0' + idx%10)
idx /= 10
if idx == 0 {
break
}
}
return string(buf[:])
}