Iteration over lists

Emil Öberg (LN/EAB) emil.oberg@REDACTED
Fri Mar 17 15:09:31 CET 2006


 I don't think you can use timer:tc() to do the measuring here. You need to measure cpu time, not elapsed. List comprehension will not suspend (if I have understood the erts correct), but the rest will, so it is natrual that it takes less real time. I used fprof with cpu_time to get the values, and that in itself will of course cause measurment differneces, (I blame Schrödinger and his cat...) but not to much. 

	/Emil

-----Original Message-----
From: owner-erlang-questions@REDACTED [mailto:owner-erlang-questions@REDACTED] On Behalf Of Bengt Kleberg
Sent: den 17 mars 2006 14:22
To: erlang-questions@REDACTED
Subject: Re: Iteration over lists

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