Debian Codegraph @

pubsub/benchmark_test.go

raw
1 // Copyright 2019 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package pubsub
16
17 import (
18 "context"
19 "errors"
20 "fmt"
21 "math/rand"
22 "sync"
23 "testing"
24 "time"
25
26 "gocloud.dev/pubsub/driver"
27 "golang.org/x/sync/errgroup"
28 )
29
30 const (
31 // How long to run the test.
32 runFor = 25 * time.Second
33 // How long the "warmup period" is, during which we report more frequently.
34 reportWarmup = 500 * time.Millisecond
35 // Minimum frequency for reporting throughput, during warmup and after that.
36 reportPeriodWarmup = 50 * time.Millisecond
37 reportPeriod = 1 * time.Second
38 // Number of output lines per test. We set this to a constant so that it's
39 // easy to copy/paste the output into a Google Sheet with pre-created graphs.
40 // Should be above runFor / reportPeriod + reportWarmup / reportPeriodWarmup.
41 numLinesPerTest = 50
42 // Number of data points to smooth msgs/sec and RPCs/sec over.
43 smoothing = 5
44 )
45
46 type fakeSub struct {
47 driver.Subscription
48 start time.Time
49 profile func(bool, int) (int, time.Duration)
50 msgs []*driver.Message
51 }
52
53 func (*fakeSub) SendAcks(ctx context.Context, ackIDs []driver.AckID) error { return nil }
54 func (*fakeSub) CanNack() bool { return false }
55 func (*fakeSub) Close() error { return nil }
56
57 func (s *fakeSub) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
58 n, delay := s.profile(s.inMiddleThird(), maxMessages)
59 if delay > 0 {
60 time.Sleep(delay)
61 }
62 return s.msgs[:n], nil
63 }
64
65 // inMiddleThird returns true if this test is in the middle third of the running
66 // time; used for burstiness tests.
67 func (s *fakeSub) inMiddleThird() bool {
68 elapsed := time.Since(s.start)
69 return elapsed > runFor/3 && elapsed < runFor*2/3
70 }
71
72 // TestReceivePerformance enables characterization of Receive under various
73 // situations, characterized in "tests" below.
74 func TestReceivePerformance(t *testing.T) {
75 t.Skip("Skipped by default")
76
77 const defaultNumGoRoutines = 100
78 defaultReceiveProfile := func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 0 }
79 defaultProcessProfile := func(bool) time.Duration { return 0 }
80
81 tests := []struct {
82 description string
83 // See the defaults above.
84 numGoRoutines int
85 receiveProfile func(bool, int) (int, time.Duration)
86 processProfile func(bool) time.Duration
87 }{
88 {
89 description: "baseline",
90 },
91 {
92 description: "1 goroutine",
93 numGoRoutines: 1,
94 },
95 {
96 description: "receive 100ms",
97 receiveProfile: func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 100 * time.Millisecond },
98 },
99 {
100 description: "receive 1s",
101 receiveProfile: func(_ bool, maxMessages int) (int, time.Duration) { return maxMessages, 1 * time.Second },
102 },
103 {
104 description: "process 100ms",
105 processProfile: func(bool) time.Duration { return 100 * time.Millisecond },
106 },
107 {
108 description: "process 1s",
109 processProfile: func(bool) time.Duration { return 1 * time.Second },
110 },
111 {
112 description: "receive 1s process 70ms",
113 receiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {
114 return maxMessages, 1 * time.Second
115 },
116 processProfile: func(bool) time.Duration { return 70 * time.Millisecond },
117 },
118 {
119 description: "receive 250ms+stddev 150ms, process 10ms + stddev 5ms",
120 receiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {
121 return maxMessages, time.Duration(rand.NormFloat64()*150+250) * time.Millisecond
122 },
123 processProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },
124 },
125 {
126 description: "bursty message arrival",
127 receiveProfile: func(inMiddleThird bool, maxMessages int) (int, time.Duration) {
128 // When in the middle third of the running time, return 0 messages.
129 n := maxMessages
130 if inMiddleThird {
131 n = 0
132 }
133 return n, time.Duration(rand.NormFloat64()*25+100) * time.Millisecond
134 },
135 processProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },
136 },
137 {
138 description: "bursty receive time",
139 receiveProfile: func(inMiddleThird bool, maxMessages int) (int, time.Duration) {
140 // When in the middle third of the running time, 10x the RPC time.
141 d := time.Duration(rand.NormFloat64()*25+100) * time.Millisecond
142 if inMiddleThird {
143 d *= 10
144 }
145 return maxMessages, d
146 },
147 processProfile: func(bool) time.Duration { return time.Duration(rand.NormFloat64()*5+10) * time.Millisecond },
148 },
149 {
150 description: "bursty process time",
151 receiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {
152 return maxMessages, time.Duration(rand.NormFloat64()*25+100) * time.Millisecond
153 },
154 processProfile: func(inMiddleThird bool) time.Duration {
155 d := time.Duration(rand.NormFloat64()*5+10) * time.Millisecond
156 if inMiddleThird {
157 d *= 100
158 }
159 return d
160 },
161 },
162 {
163 description: "intermittent",
164 receiveProfile: func(_ bool, maxMessages int) (int, time.Duration) {
165 n := rand.Int() % 2
166 return n, 250 * time.Millisecond
167 },
168 },
169 }
170
171 for _, test := range tests {
172 if test.numGoRoutines == 0 {
173 test.numGoRoutines = defaultNumGoRoutines
174 }
175 if test.receiveProfile == nil {
176 test.receiveProfile = defaultReceiveProfile
177 }
178 if test.processProfile == nil {
179 test.processProfile = defaultProcessProfile
180 }
181 t.Run(test.description, func(t *testing.T) {
182 runBenchmark(t, test.description, test.numGoRoutines, test.receiveProfile, test.processProfile)
183 })
184 }
185 }
186
187 func runBenchmark(t *testing.T, description string, numGoRoutines int, receiveProfile func(bool, int) (int, time.Duration), processProfile func(bool) time.Duration) {
188 t.Helper()
189
190 msgs := make([]*driver.Message, maxBatchSize)
191 for i := range msgs {
192 msgs[i] = &driver.Message{}
193 }
194
195 fake := &fakeSub{msgs: msgs, profile: receiveProfile, start: time.Now()}
196 sub := newSubscription(fake, nil, nil)
197 defer sub.Shutdown(context.Background())
198
199 // Header row.
200 fmt.Printf("%s\tmsgs/sec\tRPCs/sec\tbatchsize\n", description)
201
202 var mu sync.Mutex
203 start := time.Now()
204 var lastReport time.Time
205 numMsgs := 0
206 var prevMsgsPerSec, prevRPCsPerSec []float64 // last <smoothing> datapoints
207 var runningMsgsPerSec, runningRPCsPerSec float64 // sum of values in above slices
208 numRPCs := 0
209 lastMaxMessages := 0
210 nLines := 1 // header
211
212 // mu must be locked when called.
213 reportLine := func(now time.Time) {
214 elapsed := now.Sub(start)
215 elapsedSinceReport := now.Sub(lastReport)
216
217 // Smooth msgsPerSec over the last <smoothing> datapoints.
218 msgsPerSec := float64(numMsgs) / elapsedSinceReport.Seconds()
219 prevMsgsPerSec = append(prevMsgsPerSec, msgsPerSec)
220 runningMsgsPerSec += msgsPerSec
221 if len(prevMsgsPerSec) > smoothing {
222 runningMsgsPerSec -= prevMsgsPerSec[0]
223 if runningMsgsPerSec < 0 {
224 runningMsgsPerSec = 0
225 }
226 prevMsgsPerSec = prevMsgsPerSec[1:]
227 }
228
229 // Smooth rpcsPerSec over the last <smoothing> datapoints.
230 rpcsPerSec := float64(numRPCs) / elapsedSinceReport.Seconds()
231 prevRPCsPerSec = append(prevRPCsPerSec, rpcsPerSec)
232 runningRPCsPerSec += rpcsPerSec
233 if len(prevRPCsPerSec) > smoothing {
234 runningRPCsPerSec -= prevRPCsPerSec[0]
235 if runningRPCsPerSec < 0 {
236 runningRPCsPerSec = 0
237 }
238 prevRPCsPerSec = prevRPCsPerSec[1:]
239 }
240
241 fmt.Printf("%f\t%f\t%f\t%d\n", elapsed.Seconds(), runningMsgsPerSec/float64(len(prevMsgsPerSec)), runningRPCsPerSec/float64(len(prevRPCsPerSec)), lastMaxMessages)
242 nLines++
243
244 lastReport = now
245 numMsgs = 0
246 numRPCs = 0
247 }
248
249 sub.preReceiveBatchHook = func(maxMessages int) {
250 mu.Lock()
251 defer mu.Unlock()
252 lastMaxMessages = maxMessages
253 numRPCs++
254 if lastReport.IsZero() {
255 reportLine(time.Now())
256 }
257 }
258
259 ctx, cancel := context.WithTimeout(context.Background(), runFor)
260 defer cancel()
261 done := make(chan struct{})
262 go func() {
263 period := reportPeriodWarmup
264 for {
265 select {
266 case now := <-time.After(period):
267 mu.Lock()
268 reportLine(now)
269 mu.Unlock()
270 if now.Sub(start) > reportWarmup {
271 period = reportPeriod
272 }
273 case <-ctx.Done():
274 close(done)
275 return
276 }
277 }
278 }()
279
280 var grp errgroup.Group
281 for range numGoRoutines {
282 grp.Go(func() error {
283 // Each goroutine loops until ctx is canceled.
284 for {
285 m, err := sub.Receive(ctx)
286 if errors.Is(err, context.DeadlineExceeded) {
287 return nil
288 }
289 if err != nil {
290 return err
291 }
292 mu.Lock()
293 numMsgs++
294 mu.Unlock()
295 delay := processProfile(fake.inMiddleThird())
296 if delay > 0 {
297 time.Sleep(delay)
298 }
299 m.Ack()
300 }
301 })
302 }
303 if err := grp.Wait(); err != nil {
304 t.Errorf("%s: %v", description, err)
305 }
306 <-done
307 if nLines > numLinesPerTest {
308 t.Errorf("produced too many lines (%d)", nLines)
309 }
310 for n := nLines; n < numLinesPerTest; n++ {
311 fmt.Println()
312 }
313 }