For loop faster than vectorized?!

12 次查看(过去 30 天)
Arash Ali
Arash Ali 2019-6-14
回答: Arjun 2024-10-28,12:09
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
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.
I hope this will help!.

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by