Last active
December 21, 2015 13:19
-
-
Save tchap/6311650 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
// Explain the following benchmark results: | |
// | |
// Benchmark____SingleThread 10 155639126 ns/op | |
// Benchmark_MultipleThreads 5 885528027 ns/op | |
// | |
// Run on a Core i7 processor (4 cores). | |
package benchmarks | |
import ( | |
"runtime" | |
"testing" | |
) | |
const ( | |
PING int = iota | |
PONG | |
) | |
func pingPong(b *testing.B) { | |
for j := 0; j < 100000; j++ { | |
pingCh := make(chan int, 1) | |
pongCh := make(chan int, 1) | |
go func() { | |
for i := 0; i < b.N; i++ { | |
pingCh <- PING | |
<-pongCh | |
} | |
close(pingCh) | |
}() | |
go func() { | |
for i := 0; i < b.N; i++ { | |
pongCh <- PONG | |
<-pingCh | |
} | |
close(pongCh) | |
}() | |
// Wait for the goroutines to return. | |
<-pingCh | |
<-pongCh | |
} | |
} | |
func Benchmark____SingleThread(b *testing.B) { | |
pingPong(b) | |
} | |
func Benchmark_MultipleThreads(b *testing.B) { | |
// Let Go use 2 OS threads. | |
runtime.GOMAXPROCS(2) | |
defer runtime.GOMAXPROCS(1) | |
pingPong(b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment