End of function slow - Matlab Profiler
8 次查看(过去 30 天)
显示 更早的评论
Hi,
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/149077/image.png)
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.
2 个评论
Muthu Annamalai
2013-7-25
According to your profiling results, ~ 1/3 of the calls to err() function do not enter the loop. Also I wonder if having function name, variable name, and the return value set to the same identifier has something to do with it.
I'd be more creative and use different names, assuming there isn't a shortage where you live :-)
采纳的回答
Richard Brown
2013-7-25
Pretty sure you'll find it's the overhead for the function call
2 个评论
Are Mjaavatten
2018-9-5
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]];
end
end
end
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.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!