MATLAB: Speed, functions and overheads

functionoverheadspeed

Dear all,
I have noticed using functions, nested functions and sub-functions considerably decrease the speed of execution. Is it possible to decrease the overhead incurred when calling a function?
Thanks, Patrick

Best Answer

x = rand(1000, 1000);
tic;
for k = 1:1e3
m = mean(x);
end
toc;
tic;
for k = 1:1e3
m = sum(x, 1) / size(x, 1);
end
toc;
I assume, but cannot test currently, that there is a measurable difference in the timing due to the overhead for calling the M-function mean() (at least until 2009a it was an M-file).
Of course there is no magic flag to reduce the overhead, otherwise TMW would not have disabled this. So inlining the code is the only way to avoid the overhead. The resulting code is faster for the price of a reduced readability.
[EDITED] Summary of my comments:
  • When you call functions, you cannot avoid the overhead.
  • When you inline the code instead, the overhead vanishes, but other difficulties arise.
  • Tertium non datur.