Skip to content

Instantly share code, notes, and snippets.

@divan
Created September 18, 2017 20:19
Show Gist options
  • Save divan/ac8ef16ad8310fec144945e76e8e6706 to your computer and use it in GitHub Desktop.
Save divan/ac8ef16ad8310fec144945e76e8e6706 to your computer and use it in GitHub Desktop.
Branch prediction Go
$ go test -test.bench .
BenchmarkLoop-4 10000 146857 ns/op
BenchmarkLoopSorted-4 100000 19901 ns/op
PASS
ok test/branch 3.706s
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