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!

 채택된 답변

Jan
Jan 2013년 10월 8일

1 개 추천

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

Nicolas
Nicolas 2013년 10월 8일
편집: per isakson 2020년 8월 14일
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.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2013년 10월 8일

편집:

2020년 8월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by