jkndrkn / erlang-mpi

Collection of benchmarks comparing the performance of the C MPI implementation to Erlang running on a many-core SMP machine.

This URL has Read+Write access

erlang-mpi / alltoall.erl
100755 72 lines (62 sloc) 2.31 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
-module(alltoall).
-compile(export_all).
 
-include("imb.hrl").
 
run(Repetitions, Data, Processes) ->
    TimeStart = imb:time_microseconds(),
    Threads = [spawn(fun() -> loop(Data) end) || _X <- lists:seq(1, Processes)],
    [Thread ! {init, Repetitions, Threads, self()} || Thread <- Threads],
    TimeEndList = finalize(Threads),
    [TimeEnd - TimeStart || TimeEnd <- TimeEndList].
 
loop(Data) ->
    receive
        {init, Reps, Threads, Parent} ->
            ?TRACE(
                "INIT: pid: ~p reps: ~p parent: ~p threads: ~p data: ~p\n",
                [self(), Reps, Parent, Threads, size(Data)]
            ),
            alltoall(Threads, Data, self(), Reps),
            Parent ! {done, self()}
    end.
 
finalize(Processes) ->
    finalize(Processes, []).
 
finalize(Processes, Times) ->
    receive
        {done, From} ->
            TimeEnd = imb:time_microseconds(),
            IsValid = lists:member(From, Processes),
            if
                IsValid and ((length(Times) + 1) =:= length(Processes)) ->
                    ?TRACE("DONE (final): from: ~p time: ~p times: ~p~n", [From, TimeEnd, Times]),
                    [TimeEnd | Times];
                IsValid ->
                    ?TRACE("DONE: from: ~p time: ~p times: ~p~n", [From, TimeEnd, Times]),
                    finalize(Processes, [TimeEnd | Times]);
                true ->
                    finalize(Processes, Times)
            end
    end.
 
alltoall(_, _, _, 0) ->
    done;
alltoall(Threads, Data, Sender, Reps) ->
    scatter(Threads, Data, Sender),
    _DataRemote = gather(Threads),
    ?TRACE(
        "ALLTOALL(~p): pid: ~p data-remote: ~p\n",
        [Reps, self(), _DataRemote]
    ),
    alltoall(Threads, Data, Sender, Reps - 1).
 
scatter(Destinations, Data, Sender) ->
    [Destination ! {message, Data, Sender} || Destination <- Destinations].
 
gather(Sources) ->
    gather(Sources, []).
 
gather(Sources, Data) when length(Sources) =:= 0 ->
    Data;
gather([From | Sources], Data) ->
    receive
        {message, DataRemote, From} ->
            ?TRACE(
                "RECV: pid: ~p from: ~p sources: ~p data-remote: ~p data-total: ~p\n",
                [self(), From, Sources, size(DataRemote), Data]
            ),
            gather(Sources, [{From, DataRemote} | Data])
    end.