github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bench/vector/mini/vector_test.go (about) 1 package vector_test 2 3 import ( 4 "runtime" 5 "testing" 6 ) 7 8 type Struct struct{ X, Y, Z float32 } 9 type Array [3]float32 10 type ArrayStruct struct{ _0, _1, _2 float32 } 11 12 func (a Struct) Add(b Struct) Struct { return Struct{a.X + b.X, a.Y + b.Y, a.Z + b.Z} } 13 func (a Array) Add(b Array) Array { 14 r := Array{} 15 for i, bv := range b { 16 r[i] = a[i] + bv 17 } 18 return r 19 } 20 func (a Array) Add2(b Array) Array { 21 r := Array{} 22 for i := range b { 23 r[i] = a[i] + b[i] 24 } 25 return r 26 } 27 func (a Array) Add3(b Array) Array { 28 r := Array{} 29 r[0] = a[0] + b[0] 30 r[1] = a[1] + b[1] 31 r[2] = a[2] + b[2] 32 return r 33 } 34 35 func (a ArrayStruct) Len() int { return 3 } 36 func (a ArrayStruct) At(i int) float32 { 37 switch i { 38 case 0: 39 return a._0 40 case 1: 41 return a._1 42 case 2: 43 return a._2 44 default: 45 return 0 // panic("") 46 } 47 } 48 func (a *ArrayStruct) Set(i int, v float32) { 49 switch i { 50 case 0: 51 a._0 = v 52 case 1: 53 a._1 = v 54 case 2: 55 a._2 = v 56 default: 57 // panic("") 58 } 59 } 60 61 func (a ArrayStruct) Add(b ArrayStruct) ArrayStruct { 62 r := ArrayStruct{} 63 for i := 0; i < a.Len(); i++ { 64 r.Set(i, a.At(i)+b.At(i)) 65 } 66 return r 67 } 68 func (a ArrayStruct) Add3(b ArrayStruct) ArrayStruct { 69 r := ArrayStruct{} 70 r.Set(0, a.At(0)+b.At(0)) 71 r.Set(1, a.At(1)+b.At(1)) 72 r.Set(2, a.At(2)+b.At(2)) 73 return r 74 } 75 76 func BenchmarkStruct(t *testing.B) { 77 a, b := Struct{1, 1, 1}, Struct{1, 1, 1} 78 for i := 0; i < t.N; i++ { 79 a = a.Add(b) 80 } 81 runtime.KeepAlive(a) 82 runtime.KeepAlive(b) 83 } 84 85 func BenchmarkArray(t *testing.B) { 86 a, b := Array{1, 1, 1}, Array{1, 1, 1} 87 for i := 0; i < t.N; i++ { 88 a = a.Add(b) 89 } 90 runtime.KeepAlive(a) 91 runtime.KeepAlive(b) 92 } 93 func BenchmarkArray2(t *testing.B) { 94 a, b := Array{1, 1, 1}, Array{1, 1, 1} 95 for i := 0; i < t.N; i++ { 96 a = a.Add2(b) 97 } 98 runtime.KeepAlive(a) 99 runtime.KeepAlive(b) 100 } 101 func BenchmarkArray3(t *testing.B) { 102 a, b := Array{1, 1, 1}, Array{1, 1, 1} 103 for i := 0; i < t.N; i++ { 104 a = a.Add3(b) 105 } 106 runtime.KeepAlive(a) 107 runtime.KeepAlive(b) 108 } 109 110 func BenchmarkArrayStruct(t *testing.B) { 111 a, b := ArrayStruct{1, 1, 1}, ArrayStruct{1, 1, 1} 112 for i := 0; i < t.N; i++ { 113 a = a.Add(b) 114 } 115 runtime.KeepAlive(a) 116 runtime.KeepAlive(b) 117 } 118 119 func BenchmarkArrayStruct3(t *testing.B) { 120 a, b := ArrayStruct{1, 1, 1}, ArrayStruct{1, 1, 1} 121 for i := 0; i < t.N; i++ { 122 a = a.Add3(b) 123 } 124 runtime.KeepAlive(a) 125 runtime.KeepAlive(b) 126 }