Skip to content

Instantly share code, notes, and snippets.

@jbcrail
Created July 21, 2012 23:38
Show Gist options
  • Save jbcrail/3157546 to your computer and use it in GitHub Desktop.
Save jbcrail/3157546 to your computer and use it in GitHub Desktop.
Ring Benchmark in Erlang
-module(ring).
-export([run/2]).
run(N, M) ->
register(home, self()),
io:format("Starting ring processes: "),
statistics(wall_clock),
L = for(1, N, fun() -> spawn(fun() -> loop() end) end),
lists:foreach(fun(I) -> init(L, I, M) end, lists:seq(1, N)),
wait(N),
{_, Time1} = statistics(wall_clock),
io:format("~p milliseconds~n", [Time1]),
io:format("Starting ring benchmark: "),
statistics(wall_clock),
lists:nth(1, L) ! ack,
wait(N),
{_, Time2} = statistics(wall_clock),
io:format("~p milliseconds~n", [Time2]),
unregister(home).
init(Pids, I, M) ->
Next = lists:nth((I rem length(Pids)) + 1, Pids),
lists:nth(I, Pids) ! {Next, M}.
loop() ->
receive
{Next, M} ->
home ! done,
loop(Next, M)
end.
loop(_, 0) ->
home ! done;
loop(Next, M) ->
receive
ack -> Next ! ack
end,
loop(Next, M - 1).
wait(0) ->
true;
wait(N) ->
receive
done -> wait(N - 1)
end.
for(N, N, F) -> [F()];
for(I, N, F) -> [F()|for(I+1, N, F)].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment