Created
March 14, 2012 02:16
-
-
Save kortschak/2033438 to your computer and use it in GitHub Desktop.
Offset slice benchmark
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
package main | |
import ( | |
"fmt" | |
"testing" | |
) | |
// An offset slice seems to be the only way to implement the C idiom to | |
// an offset (by o) a view (v) on an array (a): | |
// int *v, o; | |
// int [n]a; | |
// v = a - o; | |
// // now v[i] is a view on a[i-o] | |
type offsetSlice struct { | |
offset int | |
slice []int | |
} | |
func (o *offsetSlice) at(i int) int { return o.slice[i-o.offset] } | |
func (o *offsetSlice) set(i, v int) { o.slice[i-o.offset] = v } | |
func directSet(b *testing.B, o *offsetSlice, l int) { | |
for i := 0; i < b.N; i++ { | |
for j := 0; j < 1e3; j++ { | |
o.slice[l-o.offset] = i | |
} | |
} | |
} | |
func methodSet(b *testing.B, o *offsetSlice, l int) { | |
for i := 0; i < b.N; i++ { | |
for j := 0; j < 1e3; j++ { | |
o.set(l, i) | |
} | |
} | |
} | |
func directAt(b *testing.B, o *offsetSlice, l int) { | |
for i := 0; i < b.N; i++ { | |
for j := 0; j < 1e3; j++ { | |
_ = o.slice[l-o.offset] | |
} | |
} | |
} | |
func methodAt(b *testing.B, o *offsetSlice, l int) { | |
for i := 0; i < b.N; i++ { | |
for j := 0; j < 1e3; j++ { | |
_ = o.at(l) | |
} | |
} | |
} | |
func main() { | |
o := &offsetSlice{ | |
slice: make([]int, 5000), | |
offset: 500, | |
} | |
for i, f := range []func(*testing.B, *offsetSlice, int){directAt, methodAt, directSet, methodSet} { | |
r := testing.Benchmark(func(b *testing.B) { | |
f := f | |
f(b, o, 1000) | |
}) | |
fmt.Printf("%s: %v ns / index\n", []string{"directAt", "methodAt", "directSet", "methodSet"}[i], float64(r.NsPerOp())/1e3) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment