Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Created April 7, 2017 14:53
Show Gist options
  • Save rogeralsing/1d9c584733a780e50329ba364f3908bd to your computer and use it in GitHub Desktop.
Save rogeralsing/1d9c584733a780e50329ba364f3908bd to your computer and use it in GitHub Desktop.
-module(pingpong).
-author("ROJO01").
-export([run/0, ping/3, pong/1]).
-define(BATCH, 100).
-define(CONCURRENCY, 20).
-define(MESSAGES, 1000000).
ping(Pong, Num, ReplyTo) ->
receive
{start, NewPong} ->
NewPong ! {start, self()},
ping(NewPong, Num, ReplyTo);
msg ->
ping_reply(Pong, Num, ReplyTo);
_ ->
throw(fail)
end.
ping_reply(_, 0, ReplyTo) ->
ReplyTo ! done;
ping_reply(Pong, N, ReplyTo) when N rem ?BATCH == 0 ->
send_batch(Pong, ?BATCH),
ping(Pong, N - 1, ReplyTo);
ping_reply(Pong, N, ReplyTo) ->
ping(Pong, N - 1, ReplyTo).
send_batch(Pong, Size) ->
case Size of
0 -> ok;
_ ->
Pong ! msg,
send_batch(Pong, Size - 1)
end.
pong(Ping) ->
receive
msg ->
Ping ! msg,
pong(Ping);
{start, NewPing} ->
pong(NewPing);
_ ->
throw(bad_message)
end.
start(ReplyTo, Times) ->
case Times of
0 -> ok;
_ ->
Pong = spawn(pingpong, pong, [undefined]),
Ping = spawn(pingpong, ping, [undefined, ?MESSAGES, ReplyTo]),
Ping ! {start, Pong},
Ping ! msg,
start(ReplyTo, Times - 1)
end.
wait(Start, Times) ->
case Times of
0 ->
End = erlang:system_time(milli_seconds),
Diff = End - Start,
TotalMessages = ?MESSAGES * ?CONCURRENCY * 2,
Throughput = round(TotalMessages / Diff * 1000),
io:fwrite("~w msg/sec.~n", [Throughput]);
_ ->
receive
done -> wait(Start, Times - 1)
end
end.
run() ->
Start = erlang:system_time(milli_seconds),
start(self(), ?CONCURRENCY),
wait(Start, ?CONCURRENCY).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment