why wrapping with anonymous function speeds up?
4 ビュー (過去 30 日間)
古いコメントを表示
I try to understand the rational behind this result. When I wrap a function within an anonymmous function, it runs almost 10 times faster (R2022a, Windows, my PC, slightly less on remote server) !
What's going on ?
testfunctioncall()
function testfunctioncall
nruns = 1e6;
a = 1;
b = 2;
%%
fun = @add;
tic;
for k=1:nruns
c = fun(a, b);
end
t1=toc;
% time with direct 1000000 calls of "add" = 0.729264 [s]
fprintf('time with direct %d calls of "add" = %f [s]\n', nruns, t1);
%%
fun = @(a,b) add(a,b);
tic;
for k=1:nruns
c = fun(a, b);
end
t2=toc;
% time with 1000000 calls of "add" wrapped in anonymous = 0.076203 [s]
fprintf('time with %d calls of "add" wrapped in anonymous = %f [s]\n', nruns, t2);
end % testfunctioncall
%% subfunction
function c = add(a, b)
c = a + b;
end
4 件のコメント
Stephen23
2022 年 3 月 30 日
A wild stab in the dark: might this have something to do with resolving overloaded functions? Perhaps the anonymous function somehow optimizes selecting the correct function in a way that is not possible with the simple function handle.
Do non-overloaded functions show the same behavior?
回答 (1 件)
Fangjun Jiang
2022 年 3 月 29 日
編集済み: Fangjun Jiang
2022 年 3 月 29 日
Don't know the exact reason, but I guess it shows that "annonymous function handle" is faster than "named function handle". It is like macro vs function, or inline vs function call? I noticed that direct function call in this case is even faster.
function testfunctioncall
nruns = 1e6;
a = 1;
b = 2;
%%
fun = @add;
tic;
for k=1:nruns
c = fun(a, b);
end
t1=toc;
% time with direct 1000000 calls of "add" = 0.729264 [s]
fprintf('time with direct %d function handle calls of "add" = %f [s]\n', nruns, t1);
%%
fun = @(a,b) add(a,b);
tic;
for k=1:nruns
c = fun(a, b);
end
t2=toc;
% time with 1000000 calls of "add" wrapped in anonymous = 0.076203 [s]
fprintf('time with %d calls of "add" wrapped in anonymous = %f [s]\n', nruns, t2);
tic;
for k=1:nruns
c = add(a, b);
end
t3=toc;
% time with 1000000 calls of "add" wrapped in anonymous = 0.076203 [s]
fprintf('time with %d function calls of "add" = %f [s]\n', nruns, t3);
end % testfunctioncall
%% subfunction
function c = add(a, b)
c = a + b;
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Startup and Shutdown についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!