这段代码不是我写的,谢谢实验室的的师妹,接下来要把树形通信应用到求Pi上去。
-module(my).
-export([main/1,temp/2,integer_to_atom/1,judge/3,ceil/1]).
main(CoreNum) -> SumDie=temp(CoreNum,1),
Time=erlang:now(),
createP(1,CoreNum,SumDie,Time),
io:format("").
temp(Num,SNum) when Num =< SNum -> SNum;
temp(Num,SNum) -> temp(Num,SNum*2).
createP(N,CoreNum,SumDie,Time) when N =:= CoreNum ->
register(integer_to_atom(N),spawn(fun() -> loopin(N,2,SumDie,CoreNum,20000,Time) end));
createP(N,CoreNum,SumDie,Time) ->
register(integer_to_atom(N),spawn(fun() -> loopin(N,2,SumDie,CoreNum,5000000,Time) end)),
createP(N+1,CoreNum,SumDie,Time).
integer_to_atom(Int) -> T=integer_to_binary(Int),
binary_to_atom(T,utf8).
loopin(Number,Die,SumDie,CoreNum,NN,Time) -> T1=erlang:now(),
xunhuan(NN),
T2=erlang:now(),
io:format("the ~p core cycle time : ~pms~n",[Number,timer:now_diff(T2,T1)/1000]),
loop(Number,Die,SumDie,CoreNum,Time).
xunhuan(0) ->ok;
xunhuan(NN)->xunhuan(NN-1).
%每个core 收发信息
loop(Number,Die,SumDie,CoreNum,Time) ->
if
Die =:= SumDie*2 -> io:format("~p need time : ~pms~n",[Number,timer:now_diff(erlang:now(),Time)/1000]);
%io:format("over");
true -> [H|L]=judge(CoreNum,Number,Die),
if
H =:= 1 -> [H2|_]=L,
{send,To,DieThat}=H2,
(integer_to_atom(To))!{Number,DieThat},
io:format("~p need time : ~pms~n",[Number,timer:now_diff(erlang:now(),Time)/1000]);
true -> [H2|_]=L,
{get,From,DieThat}=H2,
receive
{From,DieThat} -> io:format("~p get info from ~p~n",[Number,From]),
loop(Number,Die*2,SumDie,CoreNum,Time)
end
end
end.
%判断每核的收发
judge(SumCore,Number,Die) -> R=lslast(SumCore,Number,Die),
if
R =:= 1 ->
if
Number rem Die =:= 1 -> {DieThat,To}=find(Number,Die),
[1,{send,To,DieThat}];
true -> [1,{send,Number-erlang:trunc(Die/2),Die}]
end;
true ->
if
Number rem Die =:= 1 -> [0,{get,Number+erlang:trunc(Die/2),Die}];
true -> [1,{send,Number-erlang:trunc(Die/2),Die}]
end
end.
%判断最后一核信息发送给哪里
find(Number,Die) -> Current_order=ceil(Number*2/Die),
if
Current_order rem 2 =:= 0 -> {Die,Number-erlang:trunc(Die/2)};
true -> find(Number,Die*2)
end.
%计算live的核在本轮迭代中的序号,若为最后一个标记为1.
lslast(SumCores,Number,Die) -> Current_order=ceil(Number*2/Die),
Sum_order=ceil(SumCores*2/Die),
%io:format("~p ~p ~p ~p ~p~n",[SumCores,Number,Die,Current_order,Sum_order]),
if
Current_order =:= Sum_order -> 1;
true -> 0
end.
%对小数取上界,比如ceil(15.1)=16
ceil(N) -> T=trunc(N),
Temp = N-T,
case Temp =:= 0.000 of
true -> T;
false -> T+1
end.
时间: 2024-10-12 22:55:42