【问题标题】:MPI_Scatter and MPI_ReduceMPI_Scatter 和 MPI_Reduce
【发布时间】:2015-04-02 07:21:08
【问题描述】:

我正在尝试找出随机生成数字的最大值。关于这个的任何想法......

我正在使用 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;

}

【问题讨论】:

  • 您有具体的问题还是只是在此处输入代码进行审核?

标签: c mpi


【解决方案1】:

你有几个错误:

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

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

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 2015-03-01
    • 2013-10-24
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2015-09-06
    • 2013-11-30
    • 2014-01-25
    相关资源
    最近更新 更多