For loop faster than vectors?

조회 수: 21(최근 30일)
Jérôme 2021년 9월 17일
댓글: Image Analyst 2021년 9월 18일
I was thinking that for loops were usually slower than vector or matrix operations, but a simple example showed me the opposite.
Here is a comparison of different implementations of a counter. The results for five runs of the code below are the following:
0.0730 0.0608 0.0691
0.0705 0.0543 0.0669
0.0745 0.0546 0.0709
0.0756 0.0571 0.0798
0.0755 0.0573 0.0729
I am surprised to see that the function equation1 (multiplication of a vector by a scalar) is slower than counter (for loop).
I am also surprised to see that the function equation1 is slower than equation2, just because of the vector is stored in a variable.
Does anyone have an explanation?
N = 10^7;
step = 0.123456789;
f1 = @() equation1(step, N);
t1 = timeit(f1);
f2 = @() equation2(step, N);
t2 = timeit(f2);
f3 = @() counter(step, N);
t3 = timeit(f3);
disp([t1 t2 t3])
% Functions under test
function out = equation1(step, N)
n = 1:N;
out = n * step;
function out = equation2(step, N)
out = (1:N) * step;
function out = counter(step, N)
out = zeros(1,N);
out(1) = step;
for n = 2:N
out(n) = out(n-1) + step;
  댓글 수: 1
Jérôme 2021년 9월 17일
I just noticed that the results are quite different when using Run an Time. With the code below, the results are:
  • test>counter: 1.055 s
  • test>equation1: 0.097 s
  • test>equation2: 0.077 s
I guess in such situations, tic toc and timeit are more accurate measurements than the profiler.
N = 10^7;
step = 0.123456789;
out1 = equation1(step, N);
out2 = equation2(step, N);
out3 = counter(step, N);
% Functions under test
same as in the original post

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

채택된 답변

Image Analyst
Image Analyst 2021년 9월 17일
I'm not surprised. See my attached demo:
Vectorized won 403 times out of 1000 = 40.3%.
For loop won 597 times out of 1000 = 59.70%.
The average time for the vectorized method = 7.3006e-06.
The average time for the for loop method = 1.40819e-05.
It often depends on how your vectorization was done and how many elements there were. It might be one way for a handful of elements but the opposite for tens of millions of elements.
  댓글 수: 2
Image Analyst
Image Analyst 2021년 9월 18일
@Jérôme, yes it's a myth that just won't die. That said, quite often or usually vectorized is faster, and makes for smaller, cleaner code that is often, though not always, more intuitive and easier to read and understand.

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

추가 답변(0개)


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!

Translated by