Skip to content

Instantly share code, notes, and snippets.

@cooldaemon
Created December 28, 2009 06:22
Show Gist options
  • Save cooldaemon/264556 to your computer and use it in GitHub Desktop.
Save cooldaemon/264556 to your computer and use it in GitHub Desktop.
acc + tail recursion vs no acc in erlang.
-module(acc).
-author('[email protected]').
-export([test/1]).
sum1([]) -> 0;
sum1([X | XS]) when is_number(X) -> X + sum1(XS);
sum1([_X | XS]) -> sum1(XS).
sum2([], Acc) -> Acc;
sum2([X | XS], Acc) when is_number(X) -> sum2(XS, X + Acc);
sum2([_X | XS], Acc) -> sum2(XS, Acc).
test(N) ->
{
benchmark(fun () -> sum1(lists:seq(1, N)) end),
benchmark(fun () -> sum2(lists:seq(1, N), 0) end)
}.
benchmark(F) ->
lists:foreach(fun statistics/1, [runtime, wall_clock]),
Result = F(),
Times = lists:map(
fun (Type) -> {_, T} = statistics(Type), T end,
[runtime, wall_clock]
),
{Result, Times}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment