big difference in execution time in approximately the same code

6 visualizaciones (últimos 30 días)
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!

Respuesta aceptada

James Tursa
James Tursa el 5 de Nov. de 2019
Editada: James Tursa el 5 de Nov. de 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.

Más respuestas (0)

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by