Performances of nested functions

3 views (last 30 days)
Nicolas
Nicolas on 8 Oct 2013
Edited: per isakson on 14 Aug 2020
Hi,
I'm new to matlab, so I hope I'm doing this right. I tried to find a documentation about performances of nested functions, but I haven't found something satisfying for my concern.
I ran this simple code on my system (winXP, MATLAB R2010a):
function [] = testNestedFunctions()
tic;
A = 0;
for i = 1:1000000
A = i * i;
end
toc;
tic;
A = 0;
for i = 1:1000000
A = nestedFun(i);
end
toc;
function [res] = nestedFun (i)
res = i * i;
end
end
The non nested code runs in 0.002511 seconds. The code with nested functions runs in 0.198646 seconds.
Is there a reason about this significant time difference? I thought it may be related to the use of loops, which may be not optimized using the nested function, but I didn't find any information about that.
Thanks!

Accepted Answer

Jan
Jan on 8 Oct 2013
Matlab's JIT accelerator can optimize the first version, but has less power, when the code inside the loop contains calls to not built-in functions like your nested function here. The JIT is not documented and the timings might change with the Matlab release. So I guess that the JIT can recognize, that A is overwritten in each iteration in the first version, but in the 2nd case, the called function could contain side-effects.
Timings are not meaningful for such minimal examples, because you cannot draw much conclusions. I'd compare it to a subfunction and a function written to another M-file. And because optimizing experimental code is not useful, I'd compare the nested function versus inlined code for the real application.
  1 Comment
Nicolas
Nicolas on 8 Oct 2013
Edited: per isakson on 14 Aug 2020
Thank you for your answer!
Actually I showed here a minimal example for clarity but in my code, I have something like that:
function [] = foo()
A = zeros(512, 512, 'double');
for i = 1:size(A, 1)
for j = 1:size(A, 2)
A(i, j) = aDistanceCenteredAt(i-1,j) + aDistanceCenteredAt(i+1,j);
end
end
function [res] = aDistanceCenteredAt(i,j)
% distance between two histograms computed on 2 windows
end
end
In this case, the non nested version runs in 0.97 second, while the nested version runs in 2.8 seconds.

Sign in to comment.

More Answers (0)

Categories

Find more on Performance and Memory 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!