big difference in execution time in approximately the same code

1 Ansicht (letzte 30 Tage)
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!

Akzeptierte Antwort

James Tursa
James Tursa am 5 Nov. 2019
Bearbeitet: James Tursa am 5 Nov. 2019
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.

Weitere Antworten (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by