For loop faster than vectorized?!

4 ビュー (過去 30 日間)
Arash Ali
Arash Ali 2019 年 6 月 14 日
回答済み: Arjun 2024 年 10 月 28 日
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 件のコメント
KALYAN ACHARJYA
KALYAN ACHARJYA 2019 年 6 月 14 日
Read here

サインインしてコメントする。

回答 (1 件)

Arjun
Arjun 2024 年 10 月 28 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by