2015-04-02 58 views
0

我试图找到随机生成的数字的最大值。任何想法...MPI_Scatter和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; 

} 
+4

你有一个特定的问题或只是在代码抛这里进行审查? – 2015-04-02 08:50:04

回答

1

你有一些漏洞有:

  1. 您在每个过程中选择n(的不同值)。 最好在0级以内选择它,然后在其他进程中选择bcast。
  2. 在计算j时,您除以comm_sz-1而不是comm_sz
  3. 您假设n可被comm_sz整除,并且每个进程都会收到完全相同数量的数字进行处理。
  4. 你用循环去i高达comm_sz-1,而不是马上要到j

这是我能在快速浏览一下发现..