Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
"Erlang Process Message" vs "0MQ Erlang Binding inproc (NIF)"
-module(inproc_vs_message).
-author('cooldaemon@gmail.com').
-export([run/2]).
run(TryCount, SRCount) ->
MPid = spawn_link(fun message_server/0),
RPid = self(),
C = start_zmq(),
IPid = spawn_link(fun () -> inproc_server(RPid, C) end),
S = connect_inproc_server(C),
lists:foreach(
fun ({F, Arg, Name}) ->
io:fwrite("==<<~p>>==~n", [Name]),
run_benchmark(TryCount, F, [SRCount, Arg])
end,
[
{fun message/2, MPid, "message"},
{fun inproc/2, S, "inproc"}
]
),
ok = erlzmq:close(S),
lists:foreach(fun (Pid) -> Pid ! finish end, [MPid, IPid]),
stop_zmq(C).
start_zmq() ->
{ok, C} = erlzmq:context(),
C.
stop_zmq(C) ->
ok = erlzmq:term(C),
ok.
message_server() ->
receive
{req, Message, Pid} ->
Pid ! {rep, Message};
finish ->
exit(normal);
Other ->
io:fwrite("Server received unknown message: ~p~n", [Other])
end,
message_server().
inproc_server(Pid, C) ->
{ok, S} = erlzmq:socket(C, [rep, {active, true}]),
ok = erlzmq:bind(S, "inproc://tester"),
Pid ! bound,
run_inproc_server(S).
run_inproc_server(S) ->
receive
{zmq, RS, Message, []} ->
ok = erlzmq:send(RS, Message);
finish ->
ok = erlzmq:close(S),
exit(normal);
Other ->
io:fwrite("Server received unknown message: ~p~n", [Other])
end,
run_inproc_server(S).
connect_inproc_server(C) ->
{ok, S} = erlzmq:socket(C, [req, {active, true}]),
receive bound -> ok end,
ok = erlzmq:connect(S, "inproc://tester"),
S.
run_benchmark(TryCount, F, Args) ->
lists:foreach(
fun (N) ->
io:fwrite("--<count:~p>--~n", [N]),
{_Result, [RunTime, WallClock]} = benchmark(F, Args),
io:fwrite("~p(~p)ms~n", [RunTime, WallClock])
end,
lists:seq(1, TryCount)
).
benchmark(F, Args) ->
lists:foreach(fun statistics/1, [runtime, wall_clock]),
Result = apply(F, Args),
Times = lists:map(
fun (Type) -> {_, T} = statistics(Type), T end,
[runtime, wall_clock]
),
{Result, Times}.
message(0, _Pid) ->
ok;
message(SRCount, Pid) ->
Pid ! {req, <<"hello">>, self()},
receive
{rep, <<"hello">>} ->
ok;
Other ->
io:fwrite("Clinet received unknown message: ~p~n", [Other])
end,
message(SRCount-1, Pid).
inproc(0, _S) ->
ok;
inproc(SRCount, S) ->
ok = erlzmq:send(S, <<"hello">>),
receive
{zmq, _RS, <<"hello">>, []} ->
ok;
Other ->
io:fwrite("Clinet received unknown message: ~p~n", [Other])
end,
inproc(SRCount-1, S).
Mac OSX 10.7.4 (CPU: 1.7 GHz Intel Core i5, MEM: 4GB 1333 MHz DDR3)
Erlang R15B01 (erts-5.9.1) [source] [64-bit] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:true]
1> inproc_vs_message:run(3, 10000).
==<<"message">>==
--<count:1>--
30(34)ms
--<count:2>--
30(23)ms
--<count:3>--
20(22)ms
==<<"inproc">>==
--<count:1>--
1240(1923)ms
--<count:2>--
1280(1960)ms
--<count:3>--
1250(1926)ms
ok
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.