相同的功能,两个代码-哪个代码运行速度更快?令人困惑

时间:2019-05-25 18:26:22

标签: process erlang

我得到了两个创建节点环(代码中的从属)的代码,其中之一是主节点(发送消息,然后他的消息通过节点环传递,直到他再次获得消息)。主机发送M消息,并且环中有N个节点。

ringA以每个节点创建其下一个节点的方式创建环(每个进程都创建其下一个进程) ringB通过主节点创建所有其他节点(从节点)的方式创建环,然后开始发送M消息。

从理论上讲,我认为ringB会运行得更快,因为它实际上等待构建过程然后创建下一个节点,并且ringB一次创建所有节点,因此它应该稍微快一些。 在实践中,我得到ringB的速度更快,为什么?

ringA (N, M) ->
  spawn(fun ()-> master(N-1, M) end),
  io:format("").

master(N, M) ->
  SelfPid=self(),
  T1=erlang:timestamp(),
  if N>0 ->
    P=spawn(fun ()-> slave(N-1, SelfPid) end);
    true ->
      P=self()
  end,
  receive
     finishedCreatingAllnodes->
       masterRec (M, P, T1)
  end.

masterRec (M, P, T1) ->
  if M>0 ->
    P ! message,
    receive
      message ->
        masterRec (M-1, P, T1)
    end;
    true ->
      P ! shutdown,
      T2=erlang:timestamp(),
      io:format("runtime=~p  microseconds~n",
        [timer:now_diff(T2,T1)])
  end.

slave(N, MasterPid) ->
  if N>0 ->
    P=spawn(fun () -> slave(N-1, MasterPid) end);
    true ->
      MasterPid ! finishedCreatingAllnodes,
      P=MasterPid
  end,
  slaveRec (P).


slaveRec (P) ->
  receive
    message ->
      P ! message,
      slaveRec (P);
    shutdown ->
      P ! shutdown
  end.

ringB (N, M) ->
  _Master= spawn(fun () -> masterB(N-1, M) end),
  io:format("").


masterB(N, M) ->
  T1=erlang:timestamp(),
  NextNode= createSlaveRing(N, self()),
  masterRec (M, NextNode, T1).


createSlaveRing(1, NextNode) ->
  spawn (fun() -> slaveRec(NextNode) end);
createSlaveRing(N, NextNode) ->
  P=spawn (fun() -> slaveRec(NextNode) end),
  createSlaveRing(N-1, P).

0 个答案:

没有答案
相关问题