打开MPI的MPI_reduce而不是组合数组和

时间:2013-11-05 04:53:41

标签: mpi

我是Open MPI的新手。我已经制作了一个小程序,通过将数组拆分成等于进程数的数组来计算数组的总和。我的程序中的问题是每个进程正在计算其数组共享的正确总和,但单独计算的总和不是由MPI_reduce函数求和的。我尽力解决并参考了Open MPI手册,但仍有一些我可能会遗漏的东西。我会很感激任何指导。以下是我制作的节目:

#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

1 个答案:

答案 0 :(得分:0)

抱歉,我犯了一些错误,在我的程序上运行并行调试后我纠正了。在这里,我将共享代码以在M个进程上拆分长度为N的数组,其中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;
    }