Loose question, on function handles / speeding up run times.

3 次查看(过去 30 天)
This is quite a loose question but I was very surprised to find this out so thought I would ask.
I was running a script where I defined a function handle call it g, which was acctaully very simple (basically a linear function). Insdie the scrip I called a function which took as one of its inputs the function handle g, and applied it to a fixed vector of length 200. My code was taking ages to run and everytime I paused the code I found it was computing the function handle of the vector. I decided to apply g to the vector and enter this value as the input to my function (instead of the handle g itself), now my code runs much much faster... I dont really get why this is happening, is this obvious?
  2 个评论
Jan
Jan 2021-11-4
Please post a minimal working example which reproduces your observation. It is not likely, that the readers can reproduce your code exactly based on the description. Then an explanation of the effect might consern something different.
Matt J
Matt J 2021-11-4
It is not likely, that the readers can reproduce your code exactly based on the description.
Indeed, the following test seems to refute the claim.
A=rand(3000);
g=@(x) A*x(:);
x=rand(3000,1);
tic;
ver1(x,g);
toc
Elapsed time is 0.005904 seconds.
tic
ver2(g(x));
toc
Elapsed time is 0.005773 seconds.
function out=ver1(x,g)
out=g(x)+5;
end
function out=ver2(y)
out=y+5;
end

请先登录,再进行评论。

回答(1 个)

Aneela
Aneela 2024-2-20
Hi Daniel Adams,
  • The function “ver1” takes a vector “x” and a function handle “g”. When “ver1” is called, “g(x)” is computed, which is equivalent to matrix vector multiplication (A*x). Then 5 is added to each element of the resulting vector. The function handle “g” is called only once in this case.
  • In “ver2”, you are pre-computing “g(x)” outside the function and then passing the result directly to “ver2”. Then, 5 is added to each element of the input vector “y”.
The execution time in both the cases are nearly identical, and the overhead of calling the function handle "g" is negligible in this context.
In scenarios where function handles involve more complex operations or where they are used inside loops with non-vectorized code, you might see a more noticeable difference in performance.
For further details on “Vectorization”, refer to the following link.

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by