Created
January 22, 2017 16:53
-
-
Save quells/3d9fcf5d5a81e94dd7d2e909ff75e91f to your computer and use it in GitHub Desktop.
This file contains 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 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