Skip to content

Instantly share code, notes, and snippets.

@quells
Created January 22, 2017 16:53
Show Gist options
  • Save quells/3d9fcf5d5a81e94dd7d2e909ff75e91f to your computer and use it in GitHub Desktop.
Save quells/3d9fcf5d5a81e94dd7d2e909ff75e91f to your computer and use it in GitHub Desktop.
package chanSpeed
import (
"fmt"
"sync"
"testing"
"unsafe"
)
func BenchmarkChannelOneByte(b *testing.B) {
ch := make(chan byte, 4096)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for range ch {
}
}()
b.SetBytes(1)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
ch <- byte(i)
}
close(ch)
wg.Wait()
}
func BenchmarkChannelFloat64(b *testing.B) {
ch := make(chan float64, 4096)
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
for range ch {
}
}()
b.SetBytes(int64(unsafe.Sizeof(float64(0))))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
ch <- float64(i)
}
close(ch)
wg.Wait()
}
func BenchmarkChannelOneByteWrite(b *testing.B) {
ch := make(chan byte, 4096)
wg := sync.WaitGroup{}
wg.Add(1)
data := make([]byte, 4096)
go func(data []byte) {
defer wg.Done()
idx := 0
for x := range ch {
data[idx] = x
idx = (idx + 1) % 4096
}
}(data)
b.SetBytes(1)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
ch <- byte(i)
}
close(ch)
wg.Wait()
fmt.Println(data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment