summaryrefslogtreecommitdiffhomepage
path: root/util/eventbus/bench_test.go
blob: 7cd7a424184d206f7361b94dbeb7a7a32c6a09c5 (plain)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package eventbus_test

import (
	"math/rand/v2"
	"testing"

	"tailscale.com/util/eventbus"
)

func BenchmarkBasicThroughput(b *testing.B) {
	bus := eventbus.New()
	pcli := bus.Client(b.Name() + "-pub")
	scli := bus.Client(b.Name() + "-sub")

	type emptyEvent [0]byte

	// One publisher and a corresponding subscriber shoveling events as fast as
	// they can through the plumbing.
	pub := eventbus.Publish[emptyEvent](pcli)
	sub := eventbus.Subscribe[emptyEvent](scli)

	go func() {
		for {
			select {
			case <-sub.Events():
				continue
			case <-sub.Done():
				return
			}
		}
	}()

	for b.Loop() {
		pub.Publish(emptyEvent{})
	}
	bus.Close()
}

func BenchmarkSubsThroughput(b *testing.B) {
	bus := eventbus.New()
	pcli := bus.Client(b.Name() + "-pub")
	scli1 := bus.Client(b.Name() + "-sub1")
	scli2 := bus.Client(b.Name() + "-sub2")

	type emptyEvent [0]byte

	// One publisher and two subscribers shoveling events as fast as they can
	// through the plumbing.
	pub := eventbus.Publish[emptyEvent](pcli)
	sub1 := eventbus.Subscribe[emptyEvent](scli1)
	sub2 := eventbus.Subscribe[emptyEvent](scli2)

	for _, sub := range []*eventbus.Subscriber[emptyEvent]{sub1, sub2} {
		go func() {
			for {
				select {
				case <-sub.Events():
					continue
				case <-sub.Done():
					return
				}
			}
		}()
	}

	for b.Loop() {
		pub.Publish(emptyEvent{})
	}
	bus.Close()
}

func BenchmarkMultiThroughput(b *testing.B) {
	bus := eventbus.New()
	cli := bus.Client(b.Name())

	type eventA struct{}
	type eventB struct{}

	// Two disjoint event streams routed through the global order.
	apub := eventbus.Publish[eventA](cli)
	asub := eventbus.Subscribe[eventA](cli)
	bpub := eventbus.Publish[eventB](cli)
	bsub := eventbus.Subscribe[eventB](cli)

	go func() {
		for {
			select {
			case <-asub.Events():
				continue
			case <-asub.Done():
				return
			}
		}
	}()
	go func() {
		for {
			select {
			case <-bsub.Events():
				continue
			case <-bsub.Done():
				return
			}
		}
	}()

	var rng uint64
	var bits int
	for b.Loop() {
		if bits == 0 {
			rng = rand.Uint64()
			bits = 64
		}
		if rng&1 == 0 {
			apub.Publish(eventA{})
		} else {
			bpub.Publish(eventB{})
		}
		rng >>= 1
		bits--
	}
	bus.Close()
}