Created
December 19, 2016 08:42
-
-
Save dg3feiko/f57c11dca8cfe66078d71ef882cabd80 to your computer and use it in GitHub Desktop.
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 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) | |
} |
Author
dg3feiko
commented
Dec 19, 2016
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