0
我對Open MPI非常陌生。我製作了一個計算數組總和的小程序,將數組分成與進程數相等的塊。我的程序中存在的問題是,每個進程都計算其數組份額的正確總和,但個別計算的總和不會被MPI_reduce函數求和。我盡最大努力解決問題,並且參考了Open MPI手冊,但仍然可能會丟失一些東西。我會很感激任何一種指導。下面是我製作的節目:打開MPI的MPI_reduce未組合數組總和
#include "mpi.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
int n, rank, nrofProcs, i;
int sum, ans;
// 0,1,2, 3,4,5, 6,7,8, 9
int myarr[] = {1,5,9, 2,8,3, 7,4,6, 10};
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &nrofProcs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
n = 10;
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
sum = 0.0;
int remaining = n % nrofProcs;
int lower =rank*(n/nrofProcs);
int upper = (lower+(n/nrofProcs))-1;
for (i = lower; i <= upper; i++)
{
sum = sum + myarr[i];
}
if(rank==nrofProcs-1)
{
while(i<=remaining)
{
sum = sum + myarr[i];
i++;
}
}
/* (PROBLEM IS HERE, IT IS NOT COMBINING "sums") */
MPI_Reduce(&sum, &ans, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
// if (rank == 0)
printf("rank: %d, Sum ans: %d\n", rank, sum);
/* shut down MPI */
MPI_Finalize();
return 0;
}
Output:
rank: 2, Sum ans: 17
rank: 1, Sum ans: 13
rank: 0, Sum ans: 15
(輸出應該是rank: 0, Sum ans: 55
)
如果這是您的問題的正確答案,則應該標記爲已回答或撤回這個問題。 –
是的,這是正確的答案。只要我獲得stackoverflow.com的許可,我會將其標記爲答案。最初是兩天,但現在說明我可以將它標記爲明天的答案。感謝你的關心。 –