loop speed optimization (listing, nested, and vectorized)
Afficher commentaires plus anciens
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 commentaires
I checked for j = 1:1e5, I have the following times;
t1 = 10.0006 sec
t2 = 10.498 sec
t3 = 0.990168 sec
Qi Zhao
le 8 Fév 2020
Walter Roberson
le 8 Fév 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.
Réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!