writing a simple function

Luke Gorrie luke@REDACTED
Mon Sep 11 15:51:01 CEST 2000


Matthias.Lang@REDACTED 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('luke@REDACTED').

  -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