github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/bench/vector_fusing/vector_test.go (about)

     1  package vector
     2  
     3  import (
     4  	"runtime"
     5  	"testing"
     6  )
     7  
     8  type Vec3 [3]float32
     9  
    10  func (a Vec3) Add(b Vec3) Vec3 {
    11  	return Vec3{a[0] + b[0], a[1] + b[1], a[2] + b[2]}
    12  }
    13  func (a Vec3) Mul(v float32) Vec3 {
    14  	return Vec3{a[0] * v, a[1] * v, a[2] * v}
    15  }
    16  
    17  func BenchmarkAddMul(b *testing.B) {
    18  	x, y := Vec3{1, 2, 3}, Vec3{5, 6, 7}
    19  	for i := 0; i < b.N; i++ {
    20  		x = x.Add(y.Mul(0.15))
    21  	}
    22  	runtime.KeepAlive(x)
    23  	runtime.KeepAlive(y)
    24  }
    25  
    26  func BenchmarkAddMulFused(b *testing.B) {
    27  	x, y := Vec3{1, 2, 3}, Vec3{5, 6, 7}
    28  	for i := 0; i < b.N; i++ {
    29  		x[0] += y[0] * 0.15
    30  		x[1] += y[1] * 0.15
    31  		x[2] += y[2] * 0.15
    32  	}
    33  	runtime.KeepAlive(x)
    34  	runtime.KeepAlive(y)
    35  }
    36  
    37  type Vec3s struct{ X, Y, Z float32 }
    38  
    39  func (a Vec3s) Add(b Vec3s) Vec3s {
    40  	return Vec3s{a.X + b.X, a.Y + b.Y, a.Z + b.Z}
    41  }
    42  func (a Vec3s) Mul(v float32) Vec3s {
    43  	return Vec3s{a.X * v, a.Y * v, a.Z * v}
    44  }
    45  
    46  func BenchmarkStructAddMul(b *testing.B) {
    47  	x, y := Vec3s{1, 2, 3}, Vec3s{5, 6, 7}
    48  	for i := 0; i < b.N; i++ {
    49  		x = x.Add(y.Mul(0.15))
    50  	}
    51  	runtime.KeepAlive(x)
    52  	runtime.KeepAlive(y)
    53  }
    54  
    55  func BenchmarkStructAddMulFused(b *testing.B) {
    56  	x, y := Vec3s{1, 2, 3}, Vec3s{5, 6, 7}
    57  	for i := 0; i < b.N; i++ {
    58  		x.X += y.X * 0.15
    59  		x.Y += y.Y * 0.15
    60  		x.Z += y.Z * 0.15
    61  	}
    62  	runtime.KeepAlive(x)
    63  	runtime.KeepAlive(y)
    64  }