MPI_Scatter和MPI_Reduce

lrl1mhuk  于 2023-04-29  发布在  其他
关注(0)|答案(1)|浏览(118)

我在找随机生成的最大数。有什么想法吗..
我使用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;

}
tv6aics1

tv6aics11#

这里有几个bug:
1.在每个进程中选择n(不同的值)。最好在rank 0中选择它,并将其bcast到其余进程。
1.当计算j时,除以comm_sz-1而不是comm_sz
1.假设n可以被comm_sz整除,并且每个进程接收到完全相同数量的数字来处理。
1.循环时,i向上到comm_sz-1,而不是向上到j
这些是我能在快速浏览中找到的。.

相关问题