Why do composite functions lead to longer running times
1 view (last 30 days)
Show older comments
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
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.
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!