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
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
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
tic
ver2(g(x));
toc
function out=ver1(x,g)
out=g(x)+5;
end
function out=ver2(y)
out=y+5;
end
답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!