Skip to content

Instantly share code, notes, and snippets.

@tclements
Created October 7, 2020 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tclements/54fc4c6908ad189d5604dd729a8f4fc8 to your computer and use it in GitHub Desktop.
Save tclements/54fc4c6908ad189d5604dd729a8f4fc8 to your computer and use it in GitHub Desktop.
Compare 2x2 matrix multiplication methods in Julia
using BenchmarkTools. LinearAlgebra
function naive_mul!(C,A,B)
C[1,1] = A[1,1] * B[1,1] + A[1,2] * B[2,1]
C[1,2] = A[1,1] * B[1,2] + A[1,2] * B[2,2]
C[2,1] = A[2,1] * B[1,1] + A[2,2] * B[2,1]
C[2,2] = A[2,1] * B[1,2] + A[2,2] * B[2,2]
return nothing
end
function strassen_mul!(C,A,B)
M1 = (A[1,1] + A[2,2]) * (B[1,1] + B[2,2])
M2 = (A[2,1] + A[2,2]) * B[1,1]
M3 = A[1,1] * (B[1,2] - B[2,2])
M4 = A[2,2] * (B[2,1] - B[1,1])
M5 = (A[1,1] + A[1,2]) * B[2,2]
M6 = (A[2,1] - A[1,1]) * (B[1,1] + B[1,2])
M7 = (A[1,2] - A[2,2]) * (B[2,1] + B[2,2])
C[1,1] = M1 + M4 - M5 + M7
C[1,2] = M3 + M5
C[2,1] = M2 + M4
C[2,2] = M1 - M2 + M3 + M6
return nothing
end
A = rand(2,2)
B = rand(2,2)
C = zeros(2,2)
@benchmark mul!($C,$A,$B)
# BenchmarkTools.Trial:
# memory estimate: 0 bytes
# allocs estimate: 0
# --------------
# minimum time: 16.749 ns (0.00% GC)
# median time: 17.271 ns (0.00% GC)
# mean time: 17.642 ns (0.00% GC)
# maximum time: 46.273 ns (0.00% GC)
# --------------
# samples: 10000
# evals/sample: 998
@benchmark naive_mul!($C,$A,$B)
# BenchmarkTools.Trial:
# memory estimate: 0 bytes
# allocs estimate: 0
# --------------
# minimum time: 12.518 ns (0.00% GC)
# median time: 12.635 ns (0.00% GC)
# mean time: 12.886 ns (0.00% GC)
# maximum time: 52.074 ns (0.00% GC)
# --------------
# samples: 10000
# evals/sample: 999
@benchmark strassen_mul!($C,$A,$B)
# BenchmarkTools.Trial:
# memory estimate: 0 bytes
# allocs estimate: 0
# --------------
# minimum time: 14.810 ns (0.00% GC)
# median time: 14.869 ns (0.00% GC)
# mean time: 15.177 ns (0.00% GC)
# maximum time: 47.266 ns (0.00% GC)
# --------------
# samples: 10000
# evals/sample: 998
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment