Last active
February 2, 2018 06:50
-
-
Save xiongtx/e613ede785f991296a8b7898323e872f to your computer and use it in GitHub Desktop.
Erlang ring benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(ring). | |
-export([start/2]). | |
%% 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. | |
start(M, N) -> | |
[P|_] = create_ring(N), | |
T1 = erlang:monotonic_time(microsecond), | |
P ! {self(), M * N}, | |
receive | |
T2 -> io:format("μs elapsed: ~p~n", [T2 - T1]) | |
end. | |
create_ring(N) -> | |
[P|Ps] = Ring = [spawn(?MODULE, loop, [none]) || _ <- lists:seq(1, N)], | |
lists:foreach(fun({Current, Next}) -> Current ! {next, Next} end, | |
lists:zip(Ring, lists:append(Ps, [P]))), | |
Ring. | |
loop(Next) -> | |
receive | |
{next, New} -> loop(New); | |
{Init, 0} -> | |
Init ! erlang:monotonic_time(microsecond), | |
Next ! stop; | |
{Init, N} -> | |
Next ! {Init, N-1}, | |
loop(Next); | |
stop -> Next ! stop | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment