Created
September 18, 2017 20:19
-
-
Save divan/ac8ef16ad8310fec144945e76e8e6706 to your computer and use it in GitHub Desktop.
Branch prediction Go
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 -test.bench . | |
BenchmarkLoop-4 10000 146857 ns/op | |
BenchmarkLoopSorted-4 100000 19901 ns/op | |
PASS | |
ok test/branch 3.706s |
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 branch | |
import ( | |
"math/rand" | |
"sort" | |
"testing" | |
"time" | |
) | |
const N = 32768 | |
func prepareArray(toSort bool) []int { | |
data := make([]int, N, N) | |
rand.Seed(time.Now().UnixNano()) | |
for i := 0; i < N; i++ { | |
data[i] = rand.Intn(256) | |
} | |
if toSort { | |
sort.Ints(data) | |
} | |
return data | |
} | |
func runLoop(data []int) int64 { | |
var sum int64 | |
for i := 0; i < N; i++ { | |
if data[i] >= 128 { | |
sum += int64(data[i]) | |
} | |
} | |
return sum | |
} | |
func BenchmarkLoop(b *testing.B) { | |
slice := prepareArray(false) | |
for i := 0; i < b.N; i++ { | |
_ = runLoop(slice) | |
} | |
} | |
func BenchmarkLoopSorted(b *testing.B) { | |
slice := prepareArray(true) | |
for i := 0; i < b.N; i++ { | |
_ = runLoop(slice) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment