[erlang-questions] Ring Benchmark Problem

Harit Himanshu harit.subscriptions@REDACTED
Sun Jan 11 20:48:56 CET 2015


Hello there,

I need help with code review on my attempt to following problem

 Write a ring benchmark. Create N processes in a ring. Send a message round
the ring M times so that a total of N * M messages get sent. Time how long
this takes for different values of N and M.

I have not timed this yet, and guidance on recommended ways to time is very
much appreciated.

For now, following is the code for ring that I wrote. Please let me know if
there are any shortcomings or code could be written in an much idiomatic
way.

Thanks a lot
+ Harit

*Code*

-module(ring).
-author("harith").

%% API
-export([message/2]).

% create ring of N processes and
% send M messages between them
message(N, M) when is_integer(N), is_integer(M), N > 0, M > 0 ->
  Ring = create_ring(N),
  [Start | T] = Ring,
  Start ! {T, Ring, 1, M}.

create_ring(N) ->
  Processes = [spawn(fun() -> loop() end) || _ <- lists:seq(1, N)],
  [H | _] = Processes,
  lists:append(Processes, [H]).

loop() ->
  receive
    {[H | T], _L, CurrentMessage, M} ->
      io:format("~p received ~p~n", [self(), CurrentMessage]),
      H ! {T, _L, CurrentMessage, M},
      loop();
    {[], Ring, CurrentMessage, M} ->
      io:format("~p received ~p with empty list~n", [self(),
CurrentMessage]),
      case CurrentMessage < M of
        true ->
          [_ | [Next | T]] = Ring,
          NewMessage = CurrentMessage + 1,
          io:format("sending message ~p to ~p~n", [NewMessage, Next]),
          Next ! {T, Ring, NewMessage, M};
        false -> io:format("done sending ~p messages in ~p ring, taking
rest now.~n",[M, Ring])
      end,
      loop()
  end.

*Output*
1> ring:message(4, 3).
<0.33.0> received 1
{[<0.34.0>,<0.35.0>,<0.36.0>,<0.33.0>],
 [<0.33.0>,<0.34.0>,<0.35.0>,<0.36.0>,<0.33.0>],
 1,3}
<0.34.0> received 1
<0.35.0> received 1
2> <0.36.0> received 1
2> <0.33.0> received 1 with empty list
2> sending message 2 to <0.34.0>
2> <0.34.0> received 2
2> <0.35.0> received 2
2> <0.36.0> received 2
2> <0.33.0> received 2 with empty list
2> sending message 3 to <0.34.0>
2> <0.34.0> received 3
2> <0.35.0> received 3
2> <0.36.0> received 3
2> <0.33.0> received 3 with empty list
2> done sending 3 messages in
[<0.33.0>,<0.34.0>,<0.35.0>,<0.36.0>,<0.33.0>] ring, taking rest now.
2>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150111/975b9473/attachment.htm>


More information about the erlang-questions mailing list