MATLAB Answers

0

big difference in execution time in approximately the same code

Asked by Elinor Ginzburg on 5 Nov 2019
Latest activity Commented on by Elinor Ginzburg on 7 Nov 2019 at 5:58
hello,
I want to compare between two methods of matrix multiplication. I thought they ought to run approximately the same time, but when I compared their exec time, there was a noticable difference. perhaps someone could explain why is this happening and if there's a way to write it differently in order to both codes run about the same time? (I want to compare the command C=A*B where A,B,C are matrices, and the method where I multily the elements one by one)
here's my code and the traceback:
N = 1000;
A = rand(N);
B = rand(N);
%% use buildin syntax to compute output matrix
tic;
C1 = A*B;
toc;
%% calculate each element seperatly
C2 = zeros(N);
tic;
for i = 1:N
for j = 1:N
for k = 1:N
C2(i,j) = C2(i,j) + A(i,k)*B(k,j);
end
end
end
toc;
Traceback:
traceback.png
Thank you very much for your time and attention!

  0 Comments

Sign in to comment.

1 Answer

Answer by James Tursa
on 5 Nov 2019 at 16:40
Edited by James Tursa
on 5 Nov 2019 at 16:46
 Accepted Answer

The matrix multiply operator * in MATLAB calls highly optimized compiled BLAS library code in the background. The BLAS library is multi-threaded and optimized for cache hits. There is no way you will even come close to matching that for speed with anything you write by hand. Even if you wrote your loops in C/C++ and compiled it into a mex routine you would not match the BLAS library for speed. As an exercise in just comparing results, what you are doing is fine. The only way you will be able to match the MATLAB * operator for speed is to write a mex routine and call the same BLAS library (i.e., essentially duplicating what MATLAB already does).
Other linear algebra operations (e.g., backslash linear equation solving) call a related library called LAPACK.

  1 Comment

Sign in to comment.