For loop faster than vectorized?!

12 visualizaciones (últimos 30 días)
Arash Ali
Arash Ali el 14 de Jun. de 2019
Respondida: Arjun el 28 de Oct. de 2024 a las 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

Respuestas (1)

Arjun
Arjun el 28 de Oct. de 2024 a las 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!.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by