Skip to content

Instantly share code, notes, and snippets.

@nickva
Created June 16, 2023 20:55
Show Gist options
  • Select an option

  • Save nickva/169e2bfe326c19c4d80a5c38e0406a76 to your computer and use it in GitHub Desktop.

Select an option

Save nickva/169e2bfe326c19c4d80a5c38e0406a76 to your computer and use it in GitHub Desktop.
Erlang Ring Benchmark
-module(ringbench).
-export([go/2]).
go(M, N) when is_integer(M), M > 1, is_integer(N), N > 1 ->
io:format("~p processes, ~p messages~n", [N, M]),
T = erlang:monotonic_time(),
{FirstPid, FirstRef} = spawn_monitor(fun() -> first() end),
LastPid = lists:foldl(fun(_, Pid) -> spawn_link(fun() -> loop(Pid) end) end, FirstPid, lists:seq(2, N)),
io:format("processes spawned in ~p usec~n", [dt(T)]),
FirstPid ! {go, LastPid, M, erlang:monotonic_time()},
receive {'DOWN', FirstRef, _, _, _} -> ok end.
first() ->
receive {go, LastPid, I, T} -> LastPid ! {I, T}, loop(LastPid) end.
loop(NextPid) ->
receive
die ->
NextPid ! die;
{1, T} ->
io:format("messages sent in ~p us~n", [dt(T)]),
NextPid ! die;
{I, T} ->
NextPid ! {I - 1, T},
loop(NextPid)
end.
dt(T) ->
Dt = erlang:monotonic_time() - T,
erlang:convert_time_unit(Dt, native, microsecond).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment