Skip to content

Instantly share code, notes, and snippets.

@miry
Last active September 16, 2018 11:27
Show Gist options
  • Save miry/4e207a6ca3e0065fc1f1a08ec3938b24 to your computer and use it in GitHub Desktop.
Save miry/4e207a6ca3e0065fc1f1a08ec3938b24 to your computer and use it in GitHub Desktop.
package benchmarks
import (
"fmt"
"math/rand"
"testing"
)
/*
BenchmarkAccessStructure show compare metrics between data strucuture and number of items.
*/
func BenchmarkAccessStructure(b *testing.B) {
for _, size := range []int{1, 10, 100, 1000, 10000, 100000, 1000000} {
benchmarkAccessStructure(b, size)
}
}
func benchmarkAccessStructure(b *testing.B, size int) {
var indexes = make([]int, size, size)
var arr = make([]int, size, size)
var hash = make(map[int]int)
rand.Seed(size % 42)
for i := 0; i < size; i++ {
indexes[i] = rand.Intn(size)
arr[i] = i
hash[i] = i
}
b.ResetTimer()
b.Run(fmt.Sprintf("Array_%d", size), func(b *testing.B) {
for i := 0; i < b.N; i++ {
indx := indexes[i%size] % size
_ = arr[indx]
}
})
b.Run(fmt.Sprintf("Hash_%d", size), func(b *testing.B) {
for i := 0; i < b.N; i++ {
indx := indexes[i%size] % size
_ = hash[indx]
}
})
}
$ go test -bench=.
goos: darwin
goarch: amd64
pkg: github.com/miry/samples/benchmarks
BenchmarkAccessStructure/Array_1-4 100000000 25.2 ns/op
BenchmarkAccessStructure/Hash_1-4 50000000 35.5 ns/op
BenchmarkAccessStructure/Array_10-4 50000000 25.5 ns/op
BenchmarkAccessStructure/Hash_10-4 30000000 42.8 ns/op
BenchmarkAccessStructure/Array_100-4 100000000 25.2 ns/op
BenchmarkAccessStructure/Hash_100-4 30000000 43.6 ns/op
BenchmarkAccessStructure/Array_1000-4 50000000 25.5 ns/op
BenchmarkAccessStructure/Hash_1000-4 20000000 63.6 ns/op
BenchmarkAccessStructure/Array_10000-4 100000000 25.3 ns/op
BenchmarkAccessStructure/Hash_10000-4 20000000 73.1 ns/op
BenchmarkAccessStructure/Array_100000-4 50000000 25.4 ns/op
BenchmarkAccessStructure/Hash_100000-4 20000000 95.6 ns/op
BenchmarkAccessStructure/Array_1000000-4 50000000 25.3 ns/op
BenchmarkAccessStructure/Hash_1000000-4 10000000 169 ns/op
PASS
ok github.com/miry/samples/benchmarks 24.523s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment