Skip to content

Instantly share code, notes, and snippets.

@Blquinn
Created March 8, 2019 02:26
Show Gist options
  • Save Blquinn/2024a13ca80ec1d1b7990d4120413420 to your computer and use it in GitHub Desktop.
Save Blquinn/2024a13ca80ec1d1b7990d4120413420 to your computer and use it in GitHub Desktop.
Benchmark of go channels throughput
package main
import (
"testing"
"time"
)
func BenchmarkChanByteArray(b *testing.B) {
c := make(chan []byte, 1)
msg := make([]byte, 3<<10)
for i := 0; i < b.N; i++ {
c <- msg
m := <-c
b.SetBytes(int64(len(m)))
}
}
func BenchmarkChanByteArraySeparateReader(b *testing.B) {
c := make(chan []byte, 1)
msg := make([]byte, 1<<10)
d := make(chan bool)
go func() {
for m := range c {
b.SetBytes(int64(len(m)))
}
close(d)
}()
for i := 0; i < b.N; i++ {
c <- msg
}
close(c)
<-d
}
func BenchmarkChanByte(b *testing.B) {
c := make(chan byte, 1)
for i := 0; i < b.N; i++ {
c <- byte('a')
m := <-c
_ = m
b.SetBytes(1)
}
}
func BenchmarkChanByteSeparateReader(b *testing.B) {
c := make(chan byte, 1)
d := make(chan bool)
go func() {
var totalRecv int
for m := range c {
_ = m
totalRecv += 1
b.SetBytes(1)
}
close(d)
}()
for i := 0; i < b.N; i++ {
c <- byte(i)
}
close(c)
<-d
}
func BenchmarkChanByteSeparateReaderWithSelect(b *testing.B) {
c := make(chan byte, 1)
amntchan := make(chan int)
go func() {
var totalRecv int
t := time.NewTimer(time.Second)
Loop:
for {
select {
case _, ok := <-c:
if !ok {
break Loop
}
totalRecv += 1
b.SetBytes(1)
case <-t.C:
break
}
}
amntchan <- totalRecv
}()
for i := 0; i < b.N; i++ {
c <- byte(i)
}
close(c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment