Skip to content

Instantly share code, notes, and snippets.

@pocc
Last active May 26, 2019 21:13
Show Gist options
  • Save pocc/075b38f097e68ae90a07efde6de3daa5 to your computer and use it in GitHub Desktop.
Save pocc/075b38f097e68ae90a07efde6de3daa5 to your computer and use it in GitHub Desktop.
Find channel IO overhead
/* Benchmarks summing serially and then with channels
* to time how much overhead channel reads have.
* To run: `go test -bench . channel_test.go`
*/
package channel_test
import (
"sync"
"testing"
)
func BenchmarkSerial(b *testing.B) {
var sum int
for i := 0; i < b.N; i++ {
sum += i
}
}
func BenchmarkChanBuffered(b *testing.B) {
ch := make(chan int, b.N)
channelTest(b, ch)
}
func BenchmarkChanUnbuffered(b *testing.B) {
ch := make(chan int)
channelTest(b, ch)
}
func channelTest(b *testing.B, ch chan int) {
var wg sync.WaitGroup
done := make(chan bool)
wg.Add(2)
go channelOut(b.N, ch, done, &wg)
go channelIn(ch, done, &wg)
wg.Wait()
}
func channelOut(n int, ch chan<- int, done chan bool, wg *sync.WaitGroup) {
defer wg.Done()
for i := 0; i < n; i++ {
ch <- i
}
done <- true
}
func channelIn(ch <-chan int, done chan bool, wg *sync.WaitGroup) {
defer wg.Done()
var sum int
for {
select {
case num := <-ch:
sum += num
case <-done:
return
}
}
}
@pocc
Copy link
Author

pocc commented May 26, 2019

My test results on a 2015 Macbook Pro:

goos: darwin
goarch: amd64
BenchmarkSerial-8 2000000000 0.32 ns/op
BenchmarkChanBuffered-8 30000000 50.9 ns/op
BenchmarkChanUnbuffered-8 3000000 422 ns/op
PASS
ok command-line-arguments 3.998s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment