Skip to content

Instantly share code, notes, and snippets.

@dg3feiko
Created December 19, 2016 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dg3feiko/f57c11dca8cfe66078d71ef882cabd80 to your computer and use it in GitHub Desktop.
Save dg3feiko/f57c11dca8cfe66078d71ef882cabd80 to your computer and use it in GitHub Desktop.
package hello
import (
"testing"
"sync"
)
func benchmarkChannel(b *testing.B, nProducer int) {
ch := make(chan int)
var wg sync.WaitGroup
wg.Add(nProducer)
//producer
for i := 0; i < nProducer; i++ {
go func() {
for j := 0; j < b.N; j++ {
ch <- 1
}
wg.Done();
}()
}
//close signal handler
go func() {
wg.Wait();
close(ch);
}()
//consumer
var acc int = 0
for data := range ch {
acc += data
}
}
func BenchmarkChannel1(b *testing.B) {
benchmarkChannel(b, 1)
}
func BenchmarkChannel2(b *testing.B) {
benchmarkChannel(b, 2)
}
func BenchmarkChannel4(b *testing.B) {
benchmarkChannel(b, 4)
}
func BenchmarkChannel8(b *testing.B) {
benchmarkChannel(b, 8)
}
func BenchmarkChannel16(b *testing.B) {
benchmarkChannel(b, 16)
}
@dg3feiko
Copy link
Author

BenchmarkChannel1-8      5000000               242 ns/op            effective: 242 ns/op
BenchmarkChannel2-8      3000000               588 ns/op           effective: 294 ns/op
BenchmarkChannel4-8      1000000              1617 ns/op            effective: 404 ns/op
BenchmarkChannel8-8       300000              4125 ns/op            effective: 515 ns/op
BenchmarkChannel16-8      200000              9337 ns/op           effective: 583 ns/op

@dg3feiko
Copy link
Author

change ch := make(chan int) to ch := make(chan int,1024)

BenchmarkChannel1-8     20000000                92.4 ns/op
BenchmarkChannel2-8     10000000               209 ns/op
BenchmarkChannel4-8      3000000               546 ns/op
BenchmarkChannel8-8      1000000              1883 ns/op
BenchmarkChannel16-8      300000              3487 ns/op

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