perjantaina, kesäkuuta 13, 2008

My first Erlang program

I wrote a program to test how fast is the message passing and process scheduling in Erlang.

-module(pingpong).
-export([start/1, pinger/0]).

% This would be something that got its params from command line
% like: ['123']
start([PingH|_]) ->
start_pings(list_to_integer(atom_to_list(PingH)));

start(Pings) ->
start_pings(Pings).

start_pings(Pings) ->
Pid = spawn(?MODULE, pinger, []),
io:format("Processes ~w and ~w will exchange ~w pings~n", [self(), Pid, Pings]),
Pid ! { self(), Pings - 1 },
pinger().

pinger() ->
receive
{ Pid, 0 } ->
Pid ! quit,
done;
{ Pid, Pingsleft } ->
Pid ! { self(), Pingsleft - 1 },
pinger();
quit ->
done
end.

Save it into a file, like pingpong.erl, then compile with erlc pingpong.erl. Run with: time erl -noshell -s pingpong start 100000000 -s init stop

Sending 100 million messages takes roughly 60 seconds on my 1.4 GHz PowerPC Mac mini.

Ei kommentteja: