why a is function call from within a function much much slower than not doing it in a function.
Show older comments
here is a simple code that shows it:
function c=myfunc(a,b)
c=a*b;
function c=main_temp()
a(1)=5;
a(2)=8;
r=1e7;
tic
for i=1:r
c=myfunc(a(1),a(2));
end
toc
tic
for i=1:r
c=a(1)*a(2);
end
toc
end
here is the timing using tic-toc
Elapsed time is 0.327171 seconds.
Elapsed time is 0.009264 seconds.
it's about 40 times slower (for no apparent reason except function overheads). and it gets much worse when using classes (about 15 times slower then the function call).
i searched extensively around the web and read every performance post and guidances related post.
also, this is a very very simple code that shows a core problem.
2 Comments
Guillaume
on 2 Apr 2019
As Jan says, your second for loop constantly overwrites the same variable. An efficient jit compiler may simple decide to execute just the last step of the loop since all the other steps are irrelevant. However, it can't do that if you call a function since it doesn't know what happens in the function.
To make sure that it's not what happens this would probably be a better test:
function main_temp()
r=1e7;
a = rand(1, r);
b = rand(1, r);
c = zeros(1, r);
tic
for i=1:r
c(i)=myfunc(a(i),b(i));
end
toc
d = zeros(1, r);
tic
for i=1:r
d(i)=a(i)*b(i);
end
toc
end
function c=myfunc(a,b)
c=a*b;
end
>> main_temp;
Elapsed time is 0.183169 seconds.
Elapsed time is 0.044830 seconds.
Still a big impact but not as big as what you show. Functions call do have an inherant overhead and will prevent some optimisation. The nitty-gritty of it is undocumented in matlab and subject to change from version to version.
Yair Yakoby
on 2 Apr 2019
Edited: Yair Yakoby
on 3 Apr 2019
Accepted Answer
More Answers (1)
Yair Yakoby
on 3 Apr 2019
0 votes
Categories
Find more on Startup and Shutdown 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!