Last active
January 19, 2018 06:23
-
-
Save paveltyavin/f731da5981c4737c2436779212a4b55b 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
// go test -run none -bench . | |
package b | |
import ( | |
"math/rand" | |
"sort" | |
"testing" | |
) | |
const M = 8192 | |
func crunch(data []int) int { | |
var sum int | |
for _, v := range data { | |
if v > 0 { | |
sum++ | |
} | |
} | |
return sum | |
} | |
func makeRandomList() []int { | |
data := make([]int, M) | |
rand.Seed(0) | |
for i := range data { | |
data[i] = rand.Intn(2) | |
} | |
return data | |
} | |
func BenchmarkSortedArray(b *testing.B) { | |
data := makeRandomList() | |
sort.Ints(data) // sort it | |
for i := 0; i < b.N; i++ { | |
crunch(data) | |
} | |
} | |
func BenchmarkUnsortedArray(b *testing.B) { | |
data := makeRandomList() | |
for i := 0; i < b.N; i++ { | |
crunch(data) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment