public
Created

  • Download Gist
b_test.go
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
package b
 
import "testing"
 
// SIZE=1000 results (core i5 late 2011 mac mini, 10.7.3) amd64
// % go test -v -run='XXX' -bench='.'
// PASS
// BenchmarkUpdate 500000 3064 ns/op
// BenchmarkManual 500000 5143 ns/op
// BenchmarkUnroll 1000000 2927 ns/op
// BenchmarkPtr 1000000 2358 ns/op
// BenchmarkPtrUpdate 1000000 2368 ns/op
 
type E struct {
A, B, C, D int
}
 
func (e *E) update(a, b, c, d int) {
e.A += a
e.B += b
e.C += c
e.D += d
}
 
var SIZE = 1000
 
// needed to make a valid testable package
func TestNothing(t *testing.T) {}
 
func assert(e []E, b *testing.B) {
for _, v := range e {
if v.A != b.N || v.B != b.N*2 || v.C != b.N*3 || v.D != b.N*4 {
b.Fatalf("Expected: %d, %d, %d, %d; actual: %d, %d, %d, %d",
b.N, b.N*2, b.N*3, b.N*4,
v.A, v.B, v.C, v.D)
}
}
}
 
func BenchmarkUpdate(b *testing.B) {
var e = make([]E, SIZE)
for j := 0; j < b.N; j++ {
for i := range e {
e[i].update(1, 2, 3, 4)
}
}
b.StopTimer()
assert(e, b)
}
 
func BenchmarkManual(b *testing.B) {
var e = make([]E, SIZE)
for j := 0; j < b.N; j++ {
for i := range e {
e[i].A += 1
e[i].B += 2
e[i].C += 3
e[i].D += 4
}
}
b.StopTimer()
assert(e, b)
}
 
func BenchmarkUnroll(b *testing.B) {
var e = make([]E, SIZE)
for j := 0; j < b.N; j++ {
for i := range e {
v := &e[i]
v.A += 1
v.B += 2
v.C += 3
v.D += 4
}
}
b.StopTimer()
assert(e, b)
}
 
func BenchmarkPtr(b *testing.B) {
var e = make([]*E, SIZE)
for i := range e {
e[i] = &E{}
}
for j := 0; j < b.N; j++ {
for _, v := range e {
v.A += 1
v.B += 2
v.C += 3
v.D += 4
}
}
}
 
func BenchmarkPtrUpdate(b *testing.B) {
var e = make([]*E, SIZE)
for i := range e {
e[i] = &E{}
}
for j := 0; j < b.N; j++ {
for _, v := range e {
v.update(1, 2, 3, 4)
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.