Created
June 5, 2013 21:02
-
-
Save jayschwa/5717299 to your computer and use it in GitHub Desktop.
Playing with matrix performance in Go.
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" | |
import "os" | |
import "time" | |
import "runtime/pprof" | |
type Vec4 [4]float32 | |
type Mat4 [4]Vec4 | |
func (a Vec4) Scale(s float32) { | |
for i := range a { | |
a[i] *= s | |
} | |
} | |
func (a Vec4) Dot(b Vec4) float32 { | |
return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3] | |
} | |
func (m Mat4) Col(i int) Vec4 { | |
return Vec4{m[0][i], m[1][i], m[2][i], m[3][i]} | |
} | |
func (m Mat4) Row(i int) Vec4 { | |
return m[i] | |
} | |
func (a Mat4) Add(b Mat4) Mat4 { | |
return Mat4{{a[0][0] + b[0][0], a[0][1] + b[0][1], a[0][2] + b[0][2], a[0][3] + b[0][3]}, | |
{a[1][0] + b[1][0], a[1][1] + b[1][1], a[1][2] + b[1][2], a[1][3] + b[1][3]}, | |
{a[2][0] + b[2][0], a[2][1] + b[2][1], a[2][2] + b[2][2], a[2][3] + b[2][3]}, | |
{a[3][0] + b[3][0], a[3][1] + b[3][1], a[3][2] + b[3][2], a[3][3] + b[3][3]}} | |
} | |
func (a Mat4) Product(b Mat4) Mat4 { | |
b0, b1, b2, b3 := b.Col(0), b.Col(1), b.Col(2), b.Col(3) | |
return Mat4{{b0.Dot(a[0]), b1.Dot(a[0]), b2.Dot(a[0]), b3.Dot(a[0])}, | |
{b0.Dot(a[1]), b1.Dot(a[1]), b2.Dot(a[1]), b3.Dot(a[1])}, | |
{b0.Dot(a[2]), b1.Dot(a[2]), b2.Dot(a[2]), b3.Dot(a[2])}, | |
{b0.Dot(a[3]), b1.Dot(a[3]), b2.Dot(a[3]), b3.Dot(a[3])}} | |
} | |
func main() { | |
a := Mat4{{1, 2, 3, 4}, | |
{5, 6, 7, 8}, | |
{9, 10, 11, 12}, | |
{13, 14, 15, 16}} | |
b := Mat4{{17, 18, 19, 20}, | |
{21, 22, 23, 24}, | |
{25, 26, 27, 28}, | |
{29, 30, 31, 32}} | |
fmt.Println(a.Add(b)) | |
f, _ := os.Create("matrix.profile") | |
pprof.StartCPUProfile(f) | |
defer pprof.StopCPUProfile() | |
start := time.Now() | |
for i := 0; i < 1000000; i++ { | |
_ = a.Add(b) | |
} | |
fmt.Println(time.Since(start)) | |
start = time.Now() | |
for i := 0; i < 1000000; i++ { | |
_ = a.Product(b) | |
} | |
fmt.Println(time.Since(start)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment