-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmpsc_test.go
81 lines (71 loc) · 1.61 KB
/
mpsc_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
78
79
80
81
package queue_test
import (
"github.com/jakewins/4fq/pkg/queue"
"sync/atomic"
"testing"
)
func TestMPSCBasic(t *testing.T) {
q, _ := queue.NewMultiProducerSingleConsumer(queue.Options{})
slot, _ := q.NextFree()
slot.Val = 1337
q.Publish(slot)
var published []int
q.Drain(func(slot *queue.Slot) {
published = append(published, slot.Val.(int))
})
if len(published) != 1 {
t.Errorf("Expected 1 published item, found %d", len(published))
}
}
func BenchmarkMpscQueue(b *testing.B) {
producerCount := 4
runningProducers := int64(producerCount)
q, _ := queue.NewMultiProducerSingleConsumer(queue.Options{
Size: 1024,
})
go func() {
var receivedCount int
for atomic.LoadInt64(&runningProducers) > 0 {
q.Drain(func(slot *queue.Slot) {
receivedCount += 1
})
}
}()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
atomic.AddInt64(&runningProducers, 1)
i := 0
for pb.Next() {
slot, _ := q.NextFree()
slot.Val = i
q.Publish(slot)
i += 1
}
atomic.AddInt64(&runningProducers, -1)
})
atomic.AddInt64(&runningProducers, -1)
}
// For reference, same use case as above but using regular channels
func BenchmarkChannel(b *testing.B) {
producerCount := 4
runningProducers := int64(producerCount)
ch := make(chan int, 1024)
go func() {
var receivedCount int
for atomic.LoadInt64(&runningProducers) > 0 {
slot := <-ch
receivedCount += slot
}
}()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
atomic.AddInt64(&runningProducers, 1)
i := 0
for pb.Next() {
ch <- i
i += 1
}
atomic.AddInt64(&runningProducers, -1)
})
atomic.AddInt64(&runningProducers, -1)
}