Three ways to do the same integration leading to three different speeds: why?
Show older comments
Here is a code that does the trapezoid rule applied to a function on [0, 100] and where I use a random vector with 1000 entries. The integration is repeated 1 million times. The output gives my computer 3 seconds for the first method, 9 seconds for the second, and 11.5 seconds for the third.
But the only difference between the third and the first is that the third method puts the calculation into a function. The difference between the second and the first is the vector notation. I don't understand why these are leading to such different efficiencies. Moreover, I am worried about the fact that putting an identical script into a function multiples the time by a factor of three!
Here is the setup:
x = linspace(0, 100, 1000);
dx = x(2) - x(1);
y = rand(size(x));
First method:
G = 0;
tic
for j = 1:1000000
g = 2*y;
g(1) = g(1)/2;
g(end) = g(end)/2;
G = G + dx/2*sum(g);
end
toc
disp(['RUN 1: G = ', num2str(G)]);
Second method
G = 0;
tic
for j = 1:1000000
G = G + dx/2*sum([y(1) 2*y(2:end-1) y(end)]);
end
toc
disp(['RUN 2: G = ', num2str(G)]);
Third method:
G = 0;
tic
for j = 1:1000000
G = G + mytrapz_equal(dx, y);
end
toc
disp(['RUN 3: G = ', num2str(G)]);
The same function as Run 1:
function F = mytrapz_equal(dx, y)
g = 2*y;
g(1) = g(1)/2;
g(end) = g(end)/2;
F = dx/2*sum(g);
end
end
Can anybody shed some light?
Accepted Answer
More Answers (2)
Roger Stafford
on 8 Nov 2014
0 votes
As to the difference between method 1 and 2, for each of the million trips through the loop method 2 has to construct and then abandon a new 1000-element array, namely [y(1) 2*y(2:end-1) y(end)], which it then hands to 'sum' and that takes allocation time that doesn't occur in method 1. That's just a guess on my part.
You should realize that accounting for timing with differing though equivalent code is fraught with uncertainty. First the Matlab language must be translated into C (I presume) and then on your computer the C is translated via a compiler into machine language appropriate for your computer, and strange and illogical things can happen to the timing in the process. A lot depends on the particular decisions the compiler writers made in coding this translation.
Categories
Find more on Matrix Indexing 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!