Call subfunction many times: Nested or local
Afficher commentaires plus anciens
I have a question regarding performance. Consider the following code:
test1 = 0;
for k = 1:100000
test1 = testfun(test1);
end
test2 = 0;
for k = 1:100000
test2 = test2+1;
end
which uses the function
function j = testfun(i)
j=i+1;
end
Simply explained, the code does the same calculation twice, the first time using a local subfunction, the second time using a nested subfunction. In the MathWorks documentation there is an article on improving performance, and there it is recommended to use local instead of nested functions (see here).
However, when I run the above code, the first part (local function) needs about 50 times longer than the second part (nested function). So I am wondering if I maybe misunderstood something, or if there are other factors which should be considered when deciding between those two options. I kinda suspect that when a simple process is repeated many times, the nested version is more efficient, because in this case calling the local function needs more time compared to actually executing it.
I have a similar situation with a more complex subfunction which I also call many times. It has about 25 lines, but also mostly consists of basic calculations on arrays with about 1-5 entries. So far I have written it down as a nested subfunction and I was wondering if I could improve the performance by instead writing a local function, but the above test-code doesn't give me much hope.
1 commentaire
Réponse acceptée
Plus de réponses (1)
Guillaume
le 22 Oct 2018
As Matt said, there's no function call at all in your 2nd example. Function calls (nested, local, or otherwise) are expensive so not having any call is usually going to result in faster code (at the expense of readability and maintenance if the code becomes messy, do use functions!)
Adapting your example to local vs nested function, it would be something like this:
%testlocal.m
function test1 = testlocal
for k = 1:100000
test1 = testfun(test1);
end
end
%local function:
function j = testfun(i)
j = j + 1;
end
%testnested.m
function test2 = testnested
for k = 1:100000
test2 = testfun(test2);
end
%nested function (defined inside another function)
function j = testfun(i)
j = j + 1;
end
end
I would suspect that there is no significant difference betweent the execution time of the two. The main difference between nested functions and local functions is that nested functions have access to the variables in scope of the parent function, a feature that is not used in the above examples.
1 commentaire
Kai
le 22 Oct 2018
Catégories
En savoir plus sur Scope Variables and Generate Names dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!