Created
December 9, 2017 02:40
-
-
Save phemmer/428685f5366c4b71b39d1037e6124a73 to your computer and use it in GitHub Desktop.
Golang benchmark check buffered channel has ready-to-read value
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
# 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 |
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 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