Skip to content

Instantly share code, notes, and snippets.

@rogeralsing
Last active April 5, 2017 10:51
Show Gist options
  • Save rogeralsing/6390d2d748cb3e39ccb1e066db01e207 to your computer and use it in GitHub Desktop.
Save rogeralsing/6390d2d748cb3e39ccb1e066db01e207 to your computer and use it in GitHub Desktop.
-module(pingpong).
-author("ROJO01").
-export([run/0, ping/2, pong/0]).
ping(Num, ReplyTo) ->
receive
{msg, Pong} ->
case Num of
0 -> ReplyTo ! done;
N when N rem 100 == 0 ->
%% batch send messages every 100th time
%% this results in higher throughput as there is now a wave of messages
%% between ping and pong, instead of a request / response flow.
send_batch(Pong, self(), 100),
ping(Num - 1, ReplyTo);
_ ->
ping(Num - 1, ReplyTo)
end
end.
send_batch(To, From, Size) ->
case Size of
0 -> ok;
_ ->
To ! {msg, From},
send_batch(To, From, Size - 1)
end.
pong() ->
receive
{msg, Ping} ->
Ping ! {msg, self()},
pong()
end.
start(ReplyTo, Times) ->
case Times of
0 -> ok;
_ ->
Pong = spawn(pingpong, pong, []),
Ping = spawn(pingpong, ping, [messages(), ReplyTo]),
Ping ! {msg, Pong},
start(ReplyTo, Times - 1)
end.
wait(Start, Times) ->
case Times of
0 ->
End = erlang:system_time(milli_seconds),
Diff = End - Start,
%%number of messages times concurrency level times 2 (both ping and pong)
TotalMessages = messages() * concurrency() * 2,
%%throughput is total messages divided by total time(ms), times 1000 ms
Throughput = round(TotalMessages / Diff * 1000),
io:fwrite("~w msg/sec.~n", [Throughput]);
_ ->
receive
done -> wait(Start, Times - 1)
end
end.
concurrency() -> 20.
messages() -> 1000000.
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