For loop faster than vectorized?!

12 Ansichten (letzte 30 Tage)
Arash Ali
Arash Ali am 14 Jun. 2019
Beantwortet: Arjun am 28 Okt. 2024 um 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

Antworten (1)

Arjun
Arjun am 28 Okt. 2024 um 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!.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by