Performances of nested functions
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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!
0 commentaires
Réponse acceptée
Jan
le 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 commentaire
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Performance and Memory dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!