For loop faster than vectorized?!
12 ビュー (過去 30 日間)
古いコメントを表示
Hi,
Can anybody tell me why for loop is faster than vectorized form in this code? What is the fastest alternative to these?
Thanks
clear;clc;
s = rand(2,9);
DIM = 2;
iter = 100;
TIME = zeros(2,iter);
for i = iter;
x = rand(12,1);
for n =1:9
for m = 1:3
INDEX = 2*(m-1)*DIM;
%For loop
tic
for j = 1:DIM
TEMP1 = (x(INDEX+j)-s(j,n));
end
toc
%Vectorized
tic
TEMP2 = (x(INDEX+1:INDEX+DIM)-s(:,n));
toc
end
end
end
回答 (1 件)
Arjun
2024 年 10 月 28 日 12:09
Hi Arash,
I see that you are trying to compare the performance in terms of elapsed time between “for” loop and vectorized version of the same code and found out that “for” loop version is faster than the vectorized version.
The “for” loop which is used for comparison is running only for 2 iteration and this is not a very accurate performance comparison as in this case the overhead of logical addressing in vectorized approach may be far greater to see any real performance gain. The effect of vectorization is more pronounced when there are many parallel computations to be performed. Apart from this, since the loop is very small, optimizations like loop unrolling makes it very fast at run time.
For the case above, using “for” loop seems to be the right choice.
Kindly refer to this MATLAB Answer as well: https://www.mathworks.com/matlabcentral/answers/421617-why-is-vectorizing-way-slower-than-the-for-next-loop-it-replaced
I hope this will help!.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!