MPI_Scatter 和 MPI_Reduce

MPI_Scatter and MPI_Reduce

我正在尝试找出随机生成数字的最大值。对此有任何想法...

我正在使用 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. 你在每个进程中select(不同的值)n。最好是 select 它在等级 0 内并广播到其余进程。
  2. 在计算 j 时,您除以 comm_sz-1 而不是 comm_sz
  3. 您假设 n 可以被 comm_sz 整除,并且每个进程接收完全相同数量的数字来处理。
  4. 你循环 i 上升到 comm_sz-1 而不是上升到 j

这是我快速浏览后可以找到的内容..