Skip to content

Instantly share code, notes, and snippets.

@phemmer
Created December 9, 2017 02:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save phemmer/428685f5366c4b71b39d1037e6124a73 to your computer and use it in GitHub Desktop.
Save phemmer/428685f5366c4b71b39d1037e6124a73 to your computer and use it in GitHub Desktop.
Golang benchmark check buffered channel has ready-to-read value
# go test -bench=.
goos: linux
goarch: amd64
pkg: tmp/eh4
BenchmarkSelect-8 200000000 7.65 ns/op
BenchmarkLen-8 2000000000 1.07 ns/op
PASS
ok tmp/eh4 4.580s
package main
import (
"fmt"
"testing"
"time"
)
var chn = make(chan int, 1000)
func init() {
go func() {
time.Sleep(time.Hour)
chn <- 0
}()
}
func BenchmarkSelect(b *testing.B) {
for n := 0; n < b.N; n++ {
select {
case v := <-chn:
fmt.Printf("have value\n", v)
default:
}
}
}
func BenchmarkLen(b *testing.B) {
for n := 0; n < b.N; n++ {
if len(chn) != 0 {
v := <-chn
fmt.Printf("have value: %v\n", v)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment