2013-11-05 72 views
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

回答

0

對不起,我犯了一些錯誤,我在我的程序並行運行調試完畢後修正。在這裏,我分享代碼來分割一個長度爲N的M進程數組,其中N和M可以具有任何值:

/* 
An MPI program split an array of length N on M processes, where N and M can have any value  
*/ 

    #include <math.h> 
    #include "mpi.h" 
    #include <iostream> 
    #include <vector> 

    using namespace std; 

    int main(int argc, char *argv[]) 
    { 
     int n, rank, nrofProcs, i; 
     int sum, ans; 
        // 0,1,2, 3,4,5, 6,7,8, 9, 10 
     int myarr[] = {1,5,9, 2,8,3, 7,4,6,11,10}; 
     vector<int> myvec (myarr, myarr + sizeof(myarr)/sizeof(int)); 
     n = myvec.size(); // number of items in array 

     MPI_Init(&argc, &argv); 

     MPI_Comm_size(MPI_COMM_WORLD, &nrofProcs); 

     MPI_Comm_rank(MPI_COMM_WORLD, &rank); 

     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 + myvec[i]; 
     } 

     if(rank==nrofProcs-1) 
     { 
      int ctr=0; 

      while(ctr<remaining) 
      { 
      sum = sum + myvec[i]; 
      ctr++; 
      i++; 
      } 
     } 
      /* combine everyone's calculations */ 
     MPI_Reduce(&sum, &ans, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD); 


     if (rank == 0) 
      cout << "rank: " <<rank << " Sum ans: " << ans<< endl; 

     /* shut down MPI */ 
     MPI_Finalize(); 

     return 0; 
    } 
+0

如果這是您的問題的正確答案,則應該標記爲已回答或撤回這個問題。 –

+0

是的,這是正確的答案。只要我獲得stackoverflow.com的許可,我會將其標記爲答案。最初是兩天,但現在說明我可以將它標記爲明天的答案。感謝你的關心。 –