End of function slow - Matlab Profiler

25 views (last 30 days)
I'm trying to optimize my program, and I'm encountering very curious results with the Profiler. It seems that the end statement in a function is taking significantly longer than any other statement.
Below is an image from the profiler output.
ks is a 1D vector, realKa is a boolean, and everything else is just a scalar.
As you can see, end takes up more time than the two most computationally intensive lines 190 and 198 combined. Why is this?
Note: I'm quite sure it is not because of the profiler, because the profiler said the total time spent in this function was 5.252 seconds, while adding up all the times and rounding up yields 2.47 seconds. Running my program without the profiler speeds things up by close to the difference of 2.782 seconds.
Vince on 25 Jul 2013
@Muthu There is no loop; it is an if-else statement. ~1/3 goes into the if, and ~2/3 goes to the else.
I tried renaming the variables and function, and it made no impact on the runtime. :/ That was a good point though.

Sign in to comment.

Accepted Answer

Richard Brown
Richard Brown on 25 Jul 2013
Pretty sure you'll find it's the overhead for the function call
Are Mjaavatten
Are Mjaavatten on 5 Sep 2018
I ran into the same problem today, with the following function:
function [X,R] = triples(L)
% Return all pythagorean triples with total side length L
X = [];
cmin = floor(L/(1+sqrt(2)));
cmax = ceil((L-1)/2);
for c = cmin:cmax
b = round(real(0.5*(L-c+sqrt(2*L*c+c^2-L^2))));
a = L-b-c;
if a>0 && a^2+b^2 == c^2
X = [X;[a,b,c]];
Running the commands
tic;for i = 1:1000;triples(5000);end;toc
takes 0.505 seconds on my PC, using Matlab 2014b. Now, cmin is actually one too low, making the expression inside the sqrt function negative for c = cmin, which explains why I need to take the real part to avoid errors. However, if I increase cmin by one, the time goes up to 0.57 seconds. Similar differences show up for most values of L.
In the latter case, the profiler allocates much time to the end statement for the for loop. In the first case the end statement takes very little time. I think this supports the suggestion by Jan in his answer to this queation that it has to do with the JIT compilation. This is supported by the fact that in Matlab2012b, things are more as I would expect, with the narrower range version executing slightly faster.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!