Skip to content

Instantly share code, notes, and snippets.

@buryat
Created January 6, 2012 12:47
Show Gist options
  • Save buryat/1570464 to your computer and use it in GitHub Desktop.
Save buryat/1570464 to your computer and use it in GitHub Desktop.
erlang message pass through processes ring
-module(ring_bench).
-export([start/1]).
%% start([N, M])
%% Create N processes into ring and sned message round the ring M times
start([A, B]) ->
N = list_to_integer(atom_to_list(A)),
M = list_to_integer(atom_to_list(B)),
Self = self(),
Max = erlang:system_info(process_limit),
io:format("Maximum allowed processes: ~p~n", [Max]),
statistics(runtime),
statistics(wall_clock),
Pids = for(1, N, fun() -> spawn(fun() -> loop(Self, N * M) end) end),
[H | _] = Pids,
H ! {0, Pids},
receive
done ->
lists:foreach(fun(Pid) -> Pid ! die end, Pids),
{_, Time1} = statistics(runtime),
{_, Time2} = statistics(wall_clock),
U1 = Time1 / 1000,
U2 = Time2 / 1000,
io:format("Time=~p (~p) seconds~n", [U1, U2]),
init:stop()
end.
loop(Master, N) ->
receive
die ->
void;
{I, _} when I =:= N->
Master ! done;
{I, Pids} ->
[H | T] = Pids,
NextPids = lists:reverse([H | lists:reverse(T)]),
% io:format("~p ~p ~p ~n", [I, self(), NextPids]),
H ! {I+1, NextPids},
loop(Master, N)
end.
for(N, N, F) -> [F()];
for(I, N, F) -> [F()|for(I+1, N, F)].
@buryat
Copy link
Author

buryat commented Jan 6, 2012

$ erl -noshell -s ring_bench start 10000 100
Time=126.65 (217.316) seconds

Erlang version R14A
Peak memory usage is about 4.63Gb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment