github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bench/mispredict/if_test.go (about) 1 package mispredict 2 3 import ( 4 "math/rand" 5 "sort" 6 "testing" 7 ) 8 9 var input = func() []int { 10 input := make([]int, 1e4) 11 for i := range input { 12 input[i] = rand.Intn(100) 13 } 14 return input 15 }() 16 17 var sorted = func() []int { 18 sorted := make([]int, len(input)) 19 copy(sorted, input) 20 sort.Ints(sorted) 21 return sorted 22 }() 23 24 func BenchmarkRandom(b *testing.B) { 25 total := 0 26 for k := 0; k < b.N; k++ { 27 total += sum(input) 28 } 29 } 30 31 func BenchmarkSorted(b *testing.B) { 32 total := 0 33 for k := 0; k < b.N; k++ { 34 total += sum(sorted) 35 } 36 } 37 38 //go:noinline 39 func fn(v int) int { 40 if v < 50 { 41 return 0 42 } else { 43 return 1 44 } 45 } 46 47 func sum(vs []int) (total int) { 48 for _, v := range vs { 49 total += fn(v) 50 } 51 return total 52 }