Skip to content

Instantly share code, notes, and snippets.

@crast
Created March 14, 2016 02:32
Show Gist options
  • Save crast/576f11443439c90f1e26 to your computer and use it in GitHub Desktop.
Save crast/576f11443439c90f1e26 to your computer and use it in GitHub Desktop.
package main
import (
"sync"
"testing"
)
// probably not necessary, but whatever
type message struct {
arbitrary []byte
result chan error
}
func runBench(b *testing.B, c chan message, f func()) {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for completion := range c {
completion.result <- nil
}
}()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
f()
}
})
close(c)
wg.Wait()
}
func BenchmarkChanThrowaway(b *testing.B) {
dest := make(chan message, 1000)
runBench(b, dest, func() {
completion := make(chan error, 1)
dest <- message{result: completion}
<-completion
})
}
func BenchmarkChanPool(b *testing.B) {
dest := make(chan message, 1000)
pool := sync.Pool{New: func() interface{} { return make(chan error, 1) }}
runBench(b, dest, func() {
completion := pool.Get().(chan error)
dest <- message{result: completion}
<-completion
pool.Put(completion)
})
}
$ go test -parallel 8 -bench .
testing: warning: no tests to run
PASS
BenchmarkChanThrowaway-4 2000000 818 ns/op
BenchmarkChanPool-4 2000000 691 ns/op
ok producer 4.582s
$ go test -parallel 24 -bench .
testing: warning: no tests to run
PASS
BenchmarkChanThrowaway-4 2000000 774 ns/op
BenchmarkChanPool-4 2000000 701 ns/op
ok producer 4.442s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment