Comparison for/vectorization- some general advice

2 ビュー (過去 30 日間)
Damiano Capocci
Damiano Capocci 2017 年 12 月 19 日
コメント済み: Damiano Capocci 2017 年 12 月 29 日
Hi, i'm trying to vectorize my code. But i have recently found this:
clear all;
tic
k=zeros([1,10000]);
a=1:10000;
k(a)=rand;
toc
tic
g=zeros([1,10000]);
for i=1:10000;
g(i)=rand;
end
toc
Elapsed time is 0.030372 seconds.
Elapsed time is 0.013857 seconds.
(Obviously) Every time tic/toc time changes a bit but there is always this kind of gap. In Matlab a vectorized code is faster than a loop code so i dont understand this result.
On the contrary i have also found:
clear all;
tic
k=zeros([1,1000000]);
a=1:1000000;
k(a)=rand;
toc
tic
g=zeros([1,1000000]);
for i=1:1000000;
g(i)=rand;
end
toc
Elapsed time is 0.034189 seconds.
Elapsed time is 0.045542 seconds.
Maybe the for loop with preallocation is not so bad but the difference between them rises when the length of the array grows. Tell me what u think and please give me some advice for a good vectorization

採用された回答

Ramnarayan Krishnamurthy
Ramnarayan Krishnamurthy 2017 年 12 月 28 日
The result you observe could be because preallocation the second time appears to be faster than the first. So, timing each allocation separately I found a slightly different result (over 1000 runs)
clear all
tic
k=zeros([1,10000]);
toc;
tic;
a=1:10000;
k(a)=rand;
toc
tic
g=zeros([1,10000]);
toc;
tic;
for i=1:10000;
g(i)=rand;
end
toc
Elapsed time is 0.000250 seconds. % pre allocation 1
Elapsed time is 0.000238 seconds.
Elapsed time is 0.000035 seconds. % pre-allocation 2
Elapsed time is 0.000730 seconds.
Here, Vectorization appears to be faster, though, the difference is definitely pronounced when the array length is larger (10000000)
I would suggest going through the following answers and questions on vectorization:
  1 件のコメント
Damiano Capocci
Damiano Capocci 2017 年 12 月 29 日
Thank you,I'll meditate about it.Just one thing,could you see this other ask of mine
https://it.mathworks.com/matlabcentral/answers/374557-arrayfun-for-a-particukar-nested-loop-in-gpu-computing?s_tid=prof_contriblnk
Thank you

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by