big difference in execution time in approximately the same code
5 次查看(过去 30 天)
显示 更早的评论
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](https://www.mathworks.com/matlabcentral/answers/uploaded_files/246792/traceback.png)
Thank you very much for your time and attention!
0 个评论
采纳的回答
James Tursa
2019-11-5
编辑:James Tursa
2019-11-5
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!