Iteration over lists
Bengt Kleberg
bengt.kleberg@REDACTED
Fri Mar 17 15:32:57 CET 2006
On 2006-03-17 14:58, Vlad Dumitrescu XX (LN/EAB) wrote:
> Hi,
>
> For reference, my compiler does cheat :-)
that is a good compiler.
> (emacs@REDACTED)9> iter:timeing(100000).
> recursion: 1 true
> revrecursion: 15998 true
> mapfun: 15000 true
> listcompr: 1 true
>
> In any case, I think each function should be called in a separate fresh process, as Björn also pointed out. Otherwise the results might not be conclusive.
new results from new code:
recursion( 10000 ) => 2648 us 10000 length
revrecursion( 10000 ) => 2551 us 10000 length
mapfun( 10000 ) => 4521 us 10000 length
listcompr( 10000 ) => 2521 us 10000 length
recursion( 10000 ) => 2564 us 10000 length
revrecursion( 10000 ) => 2910 us 10000 length
mapfun( 10000 ) => 4988 us 10000 length
listcompr( 10000 ) => 2815 us 10000 length
recursion( 10000 ) => 2662 us 10000 length
revrecursion( 10000 ) => 2618 us 10000 length
mapfun( 10000 ) => 4501 us 10000 length
listcompr( 10000 ) => 2487 us 10000 length
bengt
new code:
-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),
Pid = erlang:self(),
Result = lists:map( fun (Function) ->
{Function, run_in_process( Pid, Function, List )}
end,
[recursion, revrecursion, mapfun, listcompr]),
lists:foreach( fun ({Function, {Time, Result_list}}) ->
io:fwrite( "~w( ~w ) => ~w us ~w length~n", [Function, Length, Time,
erlang:length(Result_list)] )
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.
run_in_process( Reply, Function, List ) ->
Fun = fun() -> time( Reply, Function, List ) end,
erlang:spawn( Fun ),
receive
Result -> Result
end.
time( Reply, Function, List ) ->
Reply ! timer:tc( ?MODULE, Function, [List] ).
More information about the erlang-questions
mailing list