Skip to content

Instantly share code, notes, and snippets.

@tsujigiri
Created March 2, 2012 12:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsujigiri/1958118 to your computer and use it in GitHub Desktop.
Save tsujigiri/1958118 to your computer and use it in GitHub Desktop.
benchmarking lists:foldl against a tail-recursive function
-module(benchmark).
-export([call_n_times/4]).
call_n_times(N, Module, Function, Args) ->
call_n_times([], N, Module, Function, Args).
call_n_times(Data, 0, _, _, _) ->
io:format("average: ~p us~n", [lists:sum(Data) / length(Data)]),
io:format("fastest: ~p us~n", [lists:min(Data)]),
io:format("slowest: ~p us~n", [lists:max(Data)]);
call_n_times(Data, N, Module, Function, Args) ->
{ NewData, _ } = timer:tc(Module, Function, Args),
call_n_times([NewData|Data], N-1, Module, Function, Args).
-module(foldl_vs_recursive).
-export([start/1]).
start([ListSize, Iterations]) ->
List = lists:seq(1, list_to_integer(atom_to_list(ListSize))),
Times = list_to_integer(atom_to_list(Iterations)),
io:format("recursive:~n"),
benchmark:call_n_times(Times, ?MODULE, recursive, [List]),
io:format("foldl:~n"),
benchmark:call_n_times(Times, ?MODULE, foldl, [List]).
recursive(List) -> recursive(List, 0).
recursive([], Acc) -> Acc;
recursive([H|T], Acc) -> recursive(T, Acc + H).
foldl(List) ->
lists:foldl(fun(I,Acc) -> Acc+I end, 0, List).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment