Last active
July 17, 2017 01:47
-
-
Save maxpert/f3c405c516ba2d4c8aa8b0695e0e054e to your computer and use it in GitHub Desktop.
Golang Pub/Sub benchmarking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package rascore | |
import ( | |
"testing" | |
"sync" | |
) | |
type info struct { | |
id int | |
} | |
type infoNode struct { | |
data interface{} | |
next *infoNode | |
} | |
func BenchmarkPubSubPrimitiveChannelsMultiple(b *testing.B) { | |
const total int = 1000 | |
wg := sync.WaitGroup{} | |
notif := make([]chan int, total) | |
rootNode := &infoNode { | |
data: nil, | |
next: nil, | |
} | |
consumer := func (n int, ch chan int, root *infoNode) { | |
for i := 0; i < b.N; i++ { | |
<- ch | |
root = root.next | |
} | |
wg.Done() | |
} | |
b.StartTimer() | |
wg.Add(total) | |
for i := 0; i < total; i++ { | |
notif[i] = make(chan int, 32) | |
go consumer(i, notif[i], rootNode) | |
} | |
r := rootNode | |
for i := 0; i < b.N; i++ { | |
r.data = &info{ | |
id: i, | |
} | |
r.next = &infoNode { | |
data: nil, | |
next: nil, | |
} | |
r = r.next | |
for j := 0; j < total; j++ { | |
notif[j] <- i | |
} | |
} | |
wg.Wait() | |
b.StopTimer() | |
} | |
func BenchmarkPubSubWaitGroupMultiple(b *testing.B) { | |
const total int = 1000 | |
barrier := sync.NewCond(&sync.Mutex{}) | |
wg := sync.WaitGroup{} | |
rootNode := &infoNode { | |
data: nil, | |
next: nil, | |
} | |
consumer := func (n int, root *infoNode) { | |
for i := 0; i < b.N; i++ { | |
barrier.L.Lock() | |
for root.next == nil { | |
barrier.Wait() | |
} | |
barrier.L.Unlock() | |
if root == nil || root.next == nil { | |
b.Errorf("Failing on iteration %v", i) | |
} | |
root = root.next | |
} | |
wg.Done() | |
} | |
b.StartTimer() | |
wg.Add(total) | |
for i := 0; i < total; i++ { | |
go consumer(i, rootNode) | |
} | |
r := rootNode | |
for i := 0; i < b.N; i++ { | |
r.data = &info{ | |
id: i, | |
} | |
barrier.L.Lock() | |
r.next = &infoNode { | |
data: nil, | |
next: nil, | |
} | |
barrier.L.Unlock() | |
r = r.next | |
barrier.Broadcast() | |
} | |
wg.Wait() | |
b.StopTimer() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment