Skip to content

Instantly share code, notes, and snippets.

@freeeve
Forked from davecheney/ arrayslice_test.go
Last active December 27, 2015 15:19
Show Gist options
  • Save freeeve/7346892 to your computer and use it in GitHub Desktop.
Save freeeve/7346892 to your computer and use it in GitHub Desktop.
package arrayslice
import "testing"
func BenchmarkArray8for(b *testing.B) {
var a [8]int
for i := 0; i < b.N; i++ {
for j := 0; j < len(a); j++ {
a[j] += j
}
}
}
func BenchmarkArray8range(b *testing.B) {
var a [8]int
for i := 0; i < b.N; i++ {
for i := range a {
a[i] += i
}
}
}
func BenchmarkSlice8for(b *testing.B) {
var s = []int{0, 0, 0, 0, 0, 0, 0, 0}
for i := 0; i < b.N; i++ {
for j, n := 0, len(s); j < n; j++ {
s[j] += j
}
}
}
func BenchmarkSlice8range(b *testing.B) {
var s = []int{0, 0, 0, 0, 0, 0, 0, 0}
for i := 0; i < b.N; i++ {
for i := range s {
s[i] += i
}
}
}
func BenchmarkSlice8unroll(b *testing.B) {
var s = []int{0, 0, 0, 0, 0, 0, 0, 0}
for i := 0; i < b.N; i++ {
s[0] += 0
s[1] += 1
s[2] += 2
s[3] += 3
s[4] += 4
s[5] += 5
s[6] += 6
s[7] += 7
}
}
func BenchmarkArray8unroll(b *testing.B) {
var a [8]int
for i := 0; i < b.N; i++ {
a[0] += 0
a[1] += 1
a[2] += 2
a[3] += 3
a[4] += 4
a[5] += 5
a[6] += 6
a[7] += 7
}
}
func BenchmarkStruct8(b *testing.B) {
var t = struct{ i0, i1, i2, i3, i4, i5, i6, i7 int }{}
for i := 0; i < b.N; i++ {
t.i0 += 0
t.i1 += 1
t.i2 += 2
t.i3 += 3
t.i4 += 4
t.i5 += 5
t.i6 += 6
t.i7 += 7
}
}
wes-macbook:arrayslice go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkArray8for 200000000 8.96 ns/op
BenchmarkArray8range 100000000 10.0 ns/op
BenchmarkSlice8for 100000000 10.1 ns/op
BenchmarkSlice8range 100000000 10.4 ns/op
BenchmarkSlice8unroll 500000000 6.02 ns/op
BenchmarkArray8unroll 500000000 2.63 ns/op
BenchmarkStruct8 1000000000 2.81 ns/op
ok _/Users/wfreeman/arrayslice 14.074s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment