loop speed optimization (listing, nested, and vectorized)

9 views (last 30 days)
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 Comments
Qi Zhao
Qi Zhao on 8 Feb 2020
This seems to be related to the total number of loops. I did some tests and updated the results in the post.
Walter Roberson
Walter Roberson on 8 Feb 2020
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.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!