Iteration over lists
Bengt Kleberg
bengt.kleberg@REDACTED
Fri Mar 17 14:21:43 CET 2006
On 2006-03-17 12:56, Robert Virding wrote:
...deleted
> I think that the list construction time is only significant here because
> what is actually done is so trivial. :-)
this is a very good insight. imho. i could be wrong :-)
so i assume we are interested in, not the time to do integer_to_list/1,
but in the time it takes to go over the list. i subsequently modified
the test to do as little as possible apart from going over the list. eg
i replaced integer_to_list/1 with something less resource intensive,
a( _A ) -> a.
in microseconds i got the following for 3 runs. the bit about ''true''
below is just a check that no cheating (by the compiler :-) took place:
recursion: 2629 true
revrecursion: 3652 true
mapfun: 3547 true
listcompr: 1737 true
recursion: 2310 true
revrecursion: 3603 true
mapfun: 3703 true
listcompr: 1692 true
recursion: 2268 true
revrecursion: 3651 true
mapfun: 3535 true
listcompr: 1685 true
bengt
-module(iter).
-export([timeing/1, main/1]).
-export([recursion/1, revrecursion/1, mapfun/1, listcompr/1]).
main( [Progname] ) ->
main( [Progname, '2'] );
main( [_Progname, Length|_T] ) ->
timeing(erlang:list_to_integer( erlang:atom_to_list(Length) )),
init:stop().
timeing( Length ) ->
List = lists:seq(1, Length),
Result = lists:map( fun (Function) ->
{Function, timer:tc( ?MODULE, Function, [List] )}
end,
[recursion, revrecursion, mapfun, listcompr]),
lists:foreach( fun ({Function, {Time, R_list}}) ->
io:fwrite( "~w: ~w ~w~n", [Function, Time, erlang:length(R_list) ==
Length] )
end,
Result ).
recursion(L) ->
recursion(L, []).
recursion([H | T], Acc) ->
recursion(T, [a(H) | Acc]);
recursion([], Acc) ->
Acc.
revrecursion(L) ->
revrecursion(L, []).
revrecursion([H | T], Acc) ->
revrecursion(T, [a(H) | Acc]);
revrecursion([], Acc) ->
lists:reverse(Acc).
mapfun(L) ->
lists:map(fun a/1, L).
listcompr(L) ->
[a(X) || X <- L].
a( _A ) -> a.
More information about the erlang-questions
mailing list