Skip to content

Commit

Permalink
add Matrix mul performance test code.
Browse files Browse the repository at this point in the history
  • Loading branch information
taketo1024 committed Oct 22, 2017
1 parent 63dc925 commit 7543dfc
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
43 changes: 43 additions & 0 deletions Sources/Matrix/Matrix.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,49 @@ public struct Matrix<R: Ring, n: _Int, m: _Int>: Module, Sequence {
}
}

public static func mul2<p>(_ a: Matrix<R, n, m>, _ b: Matrix<R, m, p>) -> Matrix<R, n, p> {
assert(a.cols == b.rows, "Mismatching matrix size.")

var grid = Array(repeating: R.zero, count: a.rows * b.cols)
for l in (0 ..< a.rows * b.cols) {
let (i, k) = (l / b.cols, l % b.cols)
var x = R.zero
for j in 0 ..< a.cols {
x = x + a[i, j] * b[j, k]
}
grid[l] = x
}

return Matrix<R, n, p>(rows: a.rows, cols: b.cols, type: (a.type == b.type) ? a.type : .Default, grid: grid)
}

public static func mul3<p>(_ a: Matrix<R, n, m>, _ b: Matrix<R, m, p>) -> Matrix<R, n, p> {
assert(a.cols == b.rows, "Mismatching matrix size.")

var grid = Array(repeating: R.zero, count: a.rows * b.cols)
var p = UnsafeMutablePointer(&grid)

for c in 0 ..< a.rows * b.cols {
let (i, j) = (c / b.cols, c % b.cols)

var (q, r) = (UnsafePointer(a.grid), UnsafePointer(b.grid))
q += a.gridIndex(i, 0)
r += b.gridIndex(0, j)

var x = R.zero
for _ in 0 ..< a.cols {
x = x + q.pointee * r.pointee
q += 1
r += b.cols
}

p.pointee = x
p += 1
}

return Matrix<R, n, p>(rows: a.rows, cols: b.cols, grid: grid)
}

public var transposed: Matrix<R, m, n> {
return Matrix<R, m, n>(rows: cols, cols: rows, type: type) { (i, j) -> R in
return self[j, i]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ class SwiftyAlgebraTests: XCTestCase {
}

func testExample() {
let A = DynamicMatrix<Z>(rows: 200, cols: 200, components:[])

SwiftyAlgebra.measure("original") {
let _ = A * A
}

SwiftyAlgebra.measure("imperative") {
let _ = Matrix.mul2(A, A)
}

SwiftyAlgebra.measure("pointer") {
let _ = Matrix.mul3(A, A)
}
}

func testPerformanceExample() {
Expand Down

0 comments on commit 7543dfc

Please sign in to comment.