why wrapping with anonymous function speeds up?

4 ビュー (過去 30 日間)
Bruno Luong
Bruno Luong 2022 年 3 月 29 日
コメント済み: Bruno Luong 2022 年 3 月 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()
time with direct 1000000 calls of "add" = 0.289378 [s] time with 1000000 calls of "add" wrapped in anonymous = 0.044015 [s]
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
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?
Bruno Luong
Bruno Luong 2022 年 3 月 30 日
change add to myadd, still same behavior.

サインインしてコメントする。

回答 (1 件)

Fangjun Jiang
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

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

製品


リリース

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by