1

我对 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

4

1 回答 1

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;
    }
于 2013-11-05T06:49:40.923 回答