Skip to content

Instantly share code, notes, and snippets.

@andyleap
Forked from davecheney/ arrayslice_test.go
Last active December 27, 2015 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyleap/7346828 to your computer and use it in GitHub Desktop.
Save andyleap/7346828 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 BenchmarkArray8unrolled(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 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 BenchmarkSlice8unrolled(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 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 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
}
}
lucky(~/src/github.com/davecheney/arrayslice) % go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkArray8for 500000000 7.92 ns/op
BenchmarkArray8range 100000000 10.7 ns/op
BenchmarkSlice8for 200000000 8.76 ns/op
BenchmarkSlice8range 200000000 8.66 ns/op
BenchmarkStruct8 1000000000 2.70 ns/op
ok github.com/davecheney/arrayslice 14.076s
go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkArray8for 100000000 17.3 ns/op
BenchmarkArray8unrolled 500000000 5.56 ns/op
BenchmarkArray8range 100000000 18.9 ns/op
BenchmarkSlice8for 100000000 26.1 ns/op
BenchmarkSlice8unrolled 50000000 20.9 ns/op
BenchmarkSlice8range 50000000 25.0 ns/op
BenchmarkStruct8 500000000 5.86 ns/op
ok _/C_/Users/Vendan/Documents/evecombot/array_slice 16.806s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment