loop speed optimization (listing, nested, and vectorized)

Hi, I'm trying to compare the speed of the following options in a for loop (calculations inside the loops are just for demonstration): (1) listing all instances, (2) nested, and (3) vectorized. To my surprise, the vectorized approach is the slowest (by a lot) and listing out all the instances is the fastest. Could you please explain the reason and suggest the best way? Thank you!
UPDATE:
It is related to the numer of loops, here are the results:
1e8
Elapsed time is 3.146123 seconds.
Elapsed time is 4.148214 seconds.
Elapsed time is 11.244397 seconds.
1e7
Elapsed time is 0.342208 seconds.
Elapsed time is 0.437387 seconds.
Elapsed time is 1.146070 seconds.
1e6
Elapsed time is 0.059215 seconds.
Elapsed time is 0.061327 seconds.
Elapsed time is 0.125843 seconds.
1e5
Elapsed time is 0.029975 seconds.
Elapsed time is 0.023310 seconds.
Elapsed time is 0.020743 seconds.
1e4
Elapsed time is 0.013493 seconds.
Elapsed time is 0.010591 seconds.
Elapsed time is 0.007906 seconds.
% speed check loop vs list-all-instance
clear all
tic
for i = 1:1e7
test(1) = 1*i^2+log(i);
test(2) = 2*i^2+log(i);
test(3) = 3*i^2+log(i);
test(4) = 4*i^2+log(i);
test(5) = 5*i^2+log(i);
test(6) = 6*i^2+log(i);
test(7) = 7*i^2+log(i);
test(8) = 8*i^2+log(i);
end
toc
clear all
tic
for i = 1:1e7
for j = 1:8
test(j) = j*i^2+log(i);
end
end
toc
clear all
j=1:8;
test=zeros(1,8);
tic
for i=1:1e7
test = j*i^2+log(i);
end
toc

댓글 수: 3

KSSV
KSSV 2020년 2월 8일
편집: KSSV 2020년 2월 8일
I checked for j = 1:1e5, I have the following times;
t1 = 10.0006 sec
t2 = 10.498 sec
t3 = 0.990168 sec
This seems to be related to the total number of loops. I did some tests and updated the results in the post.
All three versions of your code have the risk that the JIT (Just In Time Compiler) could decide to optimize them away to the last iteration.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2020년 2월 8일

댓글:

2020년 2월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by