필터 지우기
필터 지우기

Why vectorized calculations are faster than for loops?

조회 수: 30 (최근 30일)
Mikhail
Mikhail 2014년 10월 26일
댓글: Keldon Alleyne 2018년 10월 1일
Why it's faster in Matlab? Is it because better memory treating, or paralleling? If this is only due parallel computation, on single-core laptop it will be now difference between? Thanks<

답변 (1개)

Jan
Jan 2014년 10월 26일
편집: Jan 2014년 10월 26일
At first: There is no evidence that vectorized code is faster in general.
If a build-in function can be applied to a complete array, a vectorization is much faster than a loop appraoch. When large temporary arrays are required, the benefits of the vectorization can be dominated by the expensive allocation of the memory, when it does not match into the processor cache.
A secondray effect of vectorizing is that the code looks more clear, at least as a rule of thumb. A trivial example:
% Loops:
A = rand(10);
B = rand(10);
C = zeros(size(A));
for i2 = 1:size(A, 2)
for i1 = 1:size(A, 1) % Columns in the inner loop
C(i1, i2) = A(i1, i2) + B(i1, i2);
end
end
% Vectorized:
C = A + B;
The 2nd method is faster concerning the runtime, but also for the programming and debug time. There is almost no chance to create a bug and it will be very easy to understand the code, when the program needs changes in the future.
  댓글 수: 3
Mikhail
Mikhail 2014년 10월 27일
편집: Mikhail 2014년 10월 27일
I still didn't understand why it happens? Why build-in function are faster? For what (fundamental) reason it happens?
Keldon Alleyne
Keldon Alleyne 2018년 10월 1일
Multiplying matrices in loops is O(N^3), while the fastest algorithms using other methods are O(N^2.3) - O(N^2.8), which can easily explain the differences in performance.
On my laptop with Matlab 2018b I get:
Elapsed time is 0.112362 seconds.
Elapsed time is 0.214544 seconds.
Elapsed time is 0.007935 seconds.

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

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by