writing a simple function

Joe Armstrong <>
Mon Sep 11 16:03:53 CEST 2000


Ummm. I did it twice. Once with a dummy loop to assess the overhead in the
timeing process itself :-)

Thus ..

-module(time_it).

-export([time_fun/2, time_fun/3, fac/1]).

time_fun(String, Fun) -> time_fun(String, Fun, 1).

time_fun(String, Fun, N) ->
    statistics(runtime),
    time1(N, fun() -> true end),            %% <- time  a dummy loop
    {_,T1} = statistics(runtime),
    time1(N, Fun),                          %% <- and the real thing
    {_, T2} = statistics(runtime),
    %% T is in milliseconds
    io:format("T1 = ~p T2=~p~n",[T1, T2]),
    Dt = T2 - T1,                           %% the real thing - the dummy loop
    if 
	Dt =< 0 ->
	    io:format("~s took 0 -- try increasing the number of tests~n",
		      [String]);
	true ->
	    R = Dt/N,
	    io:format("~s took ~p ms~n", [String, R])
    end.

time1(0, _) -> true;
time1(N, Fun) -> Fun(),time1(N-1, Fun).

fac(0) -> 1;
fac(N) -> N * fac(N-1).

%% example

> time_it:time_fun("factorial", fun() -> time_it:fac(200) end,1000).
T1 = 0 T2=440
factorial took 0.440000 ms     

  /Joe 

--
Joe Armstrong,                       
Bluetail AB,                           tel:  +46 8-545 550 00
S:t Eriksgatan 44,                     fax:  +46 8-545 550 50
SE-112 32 Stockholm, Sweden            info: www.bluetail.com

>  writes:
> 
> > To directly answer your question, here's a program which prints
> > 'hello' 1000 times by calling the 'fwrite' function in the module
> > 'hello' 1000 times, after importing it:
> 
> .. or to slightly less directly answer it, not taking "import"
> literally in the erlang sense, here's a generic way that you might
> write such a module:
> 
>   -module(looptime).
>   -author('').
> 
>   -export([time/4, dotimes/4]).
> 
>   %% Time how long it takes to apply Function of Module to Arguments N times.
>   %% Example usage:
>   %%   looptime:time(100000, erlang, now, []).
>   %% Returns: {ok, Micros} | {error, Reason}
>   time(N, Module, Function, Arguments) ->
>       case timer:tc(?MODULE, dotimes, [N, Module, Function, Arguments]) of
>           {_, {'EXIT', R}} ->
>               {error, R};
>           {Time, _} ->
>               {ok, Time}
>       end.
> 
>   dotimes(0, M, F, A) ->
>       ok;
>   dotimes(N, M, F, A) ->
>       apply(M, F, A),
>       dotimes(N-1, M, F, A).
> 
> Cheers,
> Luke
> 

-- 




More information about the erlang-questions mailing list