For loop faster than vectors?
조회 수: 12(최근 30일)
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;
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.