Why do composite functions lead to longer running times

1 view (last 30 days)
My aim is to calculate matrix entries of the form,
M_ij= integral f_i*f_j, (here integral is just meant to replace the integral symbol)
where the f_i's are a set of given functions.
For the integration algorithm I have to provide a function handle f_i*f_j, which the integration procedure has to call multiple times to estimate the integral (adaptive algorithm by Genz et al.). My problem is that this multiple calls consume a lot of time, because my function handle is defined by composing multiple function handles instead of a direct definition.
The running time problem for composite function handles is illustrated by the following simple example
f=@(x) x.^2;
g=@(x) 3*x;
h=@(x) g(f(x)); % Equivalent to 3*(x^2)
disp('Running Time Composite Function Handles')
tic
for i=1:10^5
h(3);
end
toc
disp('Running Time Direct Function Handle')
t=@(x) 3*x^2;
tic
for i=1:10^5
t(3);
end
toc
disp('Running Time Direct Calculation')
tic
for i=1:10^5
3*3^2;
end
toc
I would like to understand where the difference in the running time comes from and if there is a possibilty to circumvent it.
Thanks
  2 Comments
Adam
Adam on 4 Mar 2015
I just ran the profile over the code with predictable results that are not overly helpful.
Basically:
'Self time (built-ins, overhead, etc.)'
is responsible for > 90% of the time taken to evaluate h. I guess Matlab just doesn't/can't optimise a composite anonymous function anywhere near as quickly as the individual functions.
I also timed the case you didn't include above:
for i = 1:10^5
res = f(3);
g(res);
end
which was considerably faster than the composite, but still slower than the single function handle with the whole expression rolled into one.
Paul Pfeiffer
Paul Pfeiffer on 4 Mar 2015
Thanks Adam. Given that the composite version of the function handle takes much more time, I would need a clever way of defining a function handle from given pieces without the indirect composition.
In terms of code, the problem has the following form (the functions f, g are dummies)
f=@(x) x(1).^2+x(2).^3.*x(3);
g=@(x) x(1)*cos(x(2))-exp(-x(3));
%9-dimensional integrand
integrand=@(x) f(x(1:3)).*g(x(4:6)).*f(x(7:9));
This represents the indirect definition of the integrand. In this case I could of course just rewrite the integrand explicetely, but I need to do this for a big set of such functions f and g such that an automatic solution is necessary. As Adam wrote with the indirect definition Matlab 'looses' 90% of the time, hence, a solution would offer a speed-up of a factor 10.

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!