[erlang-questions] Efficiency of function call

Lukas Larsson garazdawi@REDACTED
Tue Jun 17 09:18:36 CEST 2014


It is because you construct and execute the fun in the same timeslot. You
want to benchmark something like this:

F = fun() -> ok end,
%% Take start time
[F() || _ <- List]
%% Take end time

Unfortunately fun does not come for free.

Lukas



On Tue, Jun 17, 2014 at 8:43 AM, fishball <fishballian@REDACTED> wrote:

> Hi
> As I read the *Efficiency Guide*, I found something interesting:(see
> http://www.erlang.org/doc/efficiency_guide/functions.html#id67357)
>
> Here is an intentionally rough guide to the relative costs of different
> kinds of calls. It is based on benchmark figures run on Solaris/Sparc:
>
>    - Calls to local or external functions (foo(), m:foo()) are the
>    fastest kind of calls.
>
>
>    - Calling or applying a fun (Fun(), apply(Fun, [])) is about three
>    times as expensive as calling a local function.
>
>
>    - Applying an exported function (Mod:Name(), apply(Mod, Name, [])) is
>    about twice as expensive as calling a fun, or about six times as
>    expensive as calling a local function.
>
> But I get another result when I run these code in my computer:
>
> foo() ->
>     ok.
> test() ->
>     List = lists:seq(1, 50000000),
>     statistics(wall_clock),
>     statistics(runtime),
>     %% [foo() || _ <- List],                               %%test result
> 358 ~ 358
>     %% [?MODULE:foo() || _ <- List],                %%test result 358 ~
> 358
>     %% [apply(?MODULE, foo, [] || _ <- List],     %%test result 358 ~ 358
>     [apply(fun() -> ok end, []) || _ <- List],         %%test result 2247
> ~ 1716
>     {_, Time1} = statistics(wall_clock),
>     {_, Time2} = statistics(runtime),
>     io:format("calc ~p ~~ ~p~n", [Time1, Time2]).
>
> Applying a fun is even slower than apply/3, Why?
> I also notice "apply/3 must look up the code for the function to execute
> in a hash table. Therefore, it will always be slower than a direct call or
> a fun call".
> So I test in my project which include many modules and I get the same
> result.
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140617/e30acef6/attachment.htm>


More information about the erlang-questions mailing list