Erlang 环形基准测试

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.



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值