Last active
February 22, 2019 15:53
-
-
Save u2386/f485343100dac0261c8a20a4aeac7d9f to your computer and use it in GitHub Desktop.
Solution to 8.11 Problem 2 in _Programming Erlang: Software for a Concurrent World_
This file contains 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
% Write a ring benchmark. Create N processes in a ring. Send a mes- sage 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. | |
-module(ring). | |
-author(hugo). | |
-export([create_ring/2, benchmark/2]). | |
benchmark(N, M) -> | |
statistics(runtime), | |
statistics(wall_clock), | |
Entry = self(), | |
E = spawn(fun() -> create_ring(N, M, Entry) end), | |
E ! "Start", | |
receive | |
stop -> ok | |
end, | |
{_, T1} = statistics(runtime), | |
{_, T2} = statistics(wall_clock), | |
io:format("Ring benchmark for ~p processes and ~p messages | |
= ~p (~p) millisecends.~n", [N, M, T1, T2]). | |
create_ring(N, M) -> | |
io:format("Spawn Node#[~p]~n", [N]), | |
Ch = create_node(N - 1, self()), | |
loop(N, Ch, M). | |
create_ring(N, M, Entry) -> | |
create_ring(N, M), | |
Entry ! stop. | |
create_node(0, Root) -> Root; | |
create_node(N, Root) -> | |
io:format("Spawn Node#[~p]~n", [N]), | |
Ch = create_node(N - 1, Root), | |
spawn(fun() -> loop(N, Ch) end). | |
loop(Seq, Ch, M) -> | |
receive | |
stop -> | |
io:format("[Node#~p] Stop~n", [Seq]), | |
Ch ! stop, | |
ok; | |
Message when M > 0 -> | |
io:format("------ Loop ~p~n", [M]), | |
io:format("[Node~p] Get message: [~p].~n", [Seq, Message]), | |
Ch ! Message, | |
loop(Seq, Ch, M - 1); | |
_ -> | |
Ch ! stop, | |
loop(Seq, Ch) | |
end. | |
loop(Seq, Ch) -> | |
receive | |
stop -> | |
io:format("[Node~p] Stop~n", [Seq]), | |
Ch ! stop, | |
ok; | |
Message -> | |
io:format("[Node~p] Get message: [~p].~n", [Seq, Message]), | |
Ch ! Message, | |
loop(Seq, Ch) | |
end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment