why is the anonymous function slower than a function call
이전 댓글 표시
I have the following test. I run a for loop and use it to populate the sigma value of a gaussian distribution. I then either call a function or evaluate the expression directly or call a function handle or use an anonymous function. The latter is the slowest. Why?
Here is my code for the test:
% define inputs
kw.m1 = 0; % mean of gaussian
kw.A1=1; % amplitude of gaussian
x = -500:1:500; % timeline
% prepare for loop
tic
for i = 1:10:100
kw.s1 = i;
% in a for next loop generate different standard deviations for gaussians
% call functions using one of several options
switch callopt
% call function using handle
case 1
feval(@gfun,x,kw.m1,kw.A1,kw.s1);
% call function using name
case 2
gfun(x,kw.m1,kw.A1,kw.s1);
% simply use a for next loop
case 3
kw.A1*exp((-(x-kw.m1).^2)/kw.s1^2);
% anonymous
case 4
gauss = @(inp1,inp2,inp3,inp4) inp1*exp((-(inp2-inp3).^2)/inp4^2);
gauss(kw.A1,x,kw.m1,kw.s1);
end
end
runtime = toc;
and here is my function gfun
function [y] = gfun(x,m,A,s)
% create gaussian
y = A*exp((-(x-m).^2)/s^2);
채택된 답변
추가 답변 (1개)
schak
2018년 2월 19일
0 개 추천
댓글 수: 2
Jan
2018년 2월 19일
Try it. In my experiences arrayfun is nicer, but slower than direct loops.
Adam Wyatt
2020년 12월 6일
I agree with Jan, arrayfun (and cellfun) are extremely slow compared to direct loops, even in the latest version (R2020b). This may be because the for loop is optimised with the JIT compiler, whereas arrayfun has not had as much optimisation.
I also agree with Jan that arrayfun can make your code much nicer (i.e. easier to read/understand) since you it is clear what function the iteration is being applied to. It would be nice if arrayfun was optimised, and even had parallel support built it (oh well).
However, sometimes arrayfun is messier. When multiple functions need to be applied, a for loop can also be easier to understand.
카테고리
도움말 센터 및 File Exchange에서 Performance and Memory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!