Skip to content

Instantly share code, notes, and snippets.

@paveltyavin
Last active January 19, 2018 06:23
Show Gist options
  • Save paveltyavin/f731da5981c4737c2436779212a4b55b to your computer and use it in GitHub Desktop.
Save paveltyavin/f731da5981c4737c2436779212a4b55b to your computer and use it in GitHub Desktop.
// 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