MPI_Scatter和MPI_Reduce

时间:2015-04-02 07:21:09

标签: c mpi

我试图找到随机生成的数字的最大值。对此有任何想法...

我正在使用MPI_Scatter将随机生成的数字拆分为相同的进程。我正在使用MPI_Reduce从每个进程获取MAX。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <mpi.h>

#define atmost 1000


int find(int* partial_max, int from, int to){
    int i, max;
    printf("%d----%d\n", from, to);

    max = partial_max[from];

    for (i = from + 1; i <= to; i++)
        if (partial_max[i] > max)
            max = partial_max[i];

    return max;
}

int main(){
    int i, j,n, comm_sz, biggest, b, my_rank, q,result;

    //1. Declare array of size 1000
    int a[atmost];

    //2. generate random integer of 0 to 999
    srand((unsigned)time(NULL));

    n = rand() % atmost;
    //n = 10;

    for (i = 0; i <= n; i++){
        a[i] = rand() % atmost;
        printf("My Numbers: %d\n", a[i]);

        //a[i] = i;
    }

    MPI_Init(NULL, NULL);
    MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    //j is the size we will split each segment into
    j = (n / (comm_sz-1));
    int partial_max[j];
    int receive_vector[j];

    //Send random numbers equally to each process
    MPI_Scatter(a, j, MPI_INT, receive_vector,
        j, MPI_INT, 0, MPI_COMM_WORLD);

    int localmax;
    localmax = -1;
    for (i = 0; i <= comm_sz-1; i++)
        if (receive_vector[i] > localmax) 
            localmax = receive_vector[i];

    // Get Max from each process
    //MPI_Reduce(receive_vector, partial_max, j, MPI_INT, MPI_MAX, 0,       MPI_COMM_WORLD);
    MPI_Reduce(&localmax, &result, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);

    if (my_rank == 0)
    {
    /*
    biggest = -1;
    for (i = 0; i < comm_sz - 1; i++){
        if (i == comm_sz - 2)
            b = find(partial_max, i * j, n - 1);
        else
            b = find(partial_max, i * j, (i + 1) * j - 1);
        if (b > biggest)
            biggest = b;
    }*/
    printf("-------------------\n");
    printf("The biggest is: %d\n", result);
    printf("The n is: %d\n", n);
}

    MPI_Finalize();

    return 0;

}

1 个答案:

答案 0 :(得分:1)

你的错误很少:

  1. 您在每个流程中选择n(不同的值)。它更好 在等级0中选择它并投射到剩余的过程。
  2. 在计算j时,您需要comm_sz-1代替comm_sz
  3. 您认为n可以被comm_sz整除,并且每个进程都会收到完全相同的数字来处理。
  4. 您循环i前往comm_sz-1而非上升到j
  5. 这是我能快速找到的......