Erlang 环形基准测试
在一个环中创建 N 个进程, 沿着环发送一条消息 M 次, 最后总共发送 N * M 条消息, 在 N M 不同取值下所用时间
代码如下
%%nest.erl
-module(nest).
-author({lustre}).
-export([start/2]).
% -compile(export_all).
create(1, Pid) -> Pid;
create(N, Pid) -> create(N-1, spawn(fun()-> loop(Pid) end)).
for(1, Fun) -> Fun();
for(N, Fun) -> [Fun() | for(N-1, Fun)].
rootLoop(State, Times, N) ->
receive
stop ->
if
is_pid(State) ->
State ! stop,
void;
true -> void
end;
%% dom send
{set, Pid} when is_pid(Pid) ->
% io:format("Has Set Pid~n"),
rootLoop(Pid, Times, N);
% %% loop send msg
{send, _Msg} when Times < N ->
% io:format("Back~n"),
rootLoop(State, Times + 1, N);
{send, _Msg} when Times =:= N ->
{_ ,Time} = statistics(wall_clock),
io:format("Loop message use: ~p msec.~n", [Time]),
io:format("Finished~n"),
State ! stop,
void;
Msg when is_pid(State) ->
State ! {send, Msg},
rootLoop(State, Times, N);
_any ->
rootLoop(State, Times, N)
end.
loop(Next) ->
receive
stop ->
Next ! stop,
% io:format("Stoped~n"),
void;
{send, Msg} ->
% io:format("Get Msg~n"),
Next ! {send, Msg},
loop(Next);
_Any -> loop(Next)
end.
%% API
start(N, M) ->
R = spawn(fun()-> rootLoop(true, 1, M) end),
statistics(wall_clock),
R ! {set, create(N, R)},
{_ ,Time} = statistics(wall_clock),
io:format("spawn process use: ~p msec.~n", [Time]),
for(M, fun()-> R ! test end),
R.