Why is manually adding elements of a vector faster than passing a vector range to sum()?

10 views (last 30 days)
>> v1 = [1,2,3,4,5];
>> tic;for i=1:10000000; sum(v1(2:5)); end;toc;
Elapsed time is 1.832466 seconds.
>> tic;for i=1:10000000; v1(2)+v1(3)+v1(4)+v1(5); end;toc;
Elapsed time is 0.446315 seconds.
I am implementing a modified version of Dynamic Time Warping and need to do a lot of summations of parts of vectors, its very slow. As I am doing this moving through a matrix, I can manually do the summation, I have to do a range based on the loop variables, i.e. sum(v1(i:i+5)), which from the example code you can see is much slower. I am also using cumsum() on part of a vector, similarly slow.
Any suggestions of how I can speed this up?
  3 Comments
Walter Roberson
Walter Roberson on 19 Mar 2019
sum([v(1:end-4); v(2:end-3); v(3:end-2); v(4:end-1); v(5:end)])
to do all of them at once.
See also movsum()

Sign in to comment.

Answers (1)

Jan
Jan on 19 Mar 2019
v1(2:5) creates a temporary vector. Some timings looks, like 2:5 is not created, but the indexing is done transparently. Then calling the function sum() costs some time also: The inputs must be parsed - or without inputs, as in your case, default values must be created.
The JIT acceleration is not documented. I assume, the explicite sum can be evaluated more efficiently, because it is less flexible. Maybe some unrolled loops can accelerate the full code, but this is not sure. Some tiny artificial test computations do not reflect the actual efficiency of the computations.

Categories

Find more on Line Plots 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!