使用MPI在二维数组中查找最小值

时间:2020-04-09 11:32:33

标签: c mpi

最近开始研究MPI技术 任务是在矩阵中找到最小值。 搜索本身可以并行化以加快工作速度。 但是我不能决定如何从程序的顺序版本中创建并行版本 我寻求帮助

#include <stdio.h>
#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int rows, cols, min, value, n;
int done = 0, numprocs, rank, i, j;
srand(time(NULL));
double startwtime = 0.0, endwtime; 
int namelen; 
char processor_name[MPI_MAX_PROCESSOR_NAME]; 
MPI_Init(&argc,&argv); 
MPI_Comm_size(MPI_COMM_WORLD,&numprocs); 
MPI_Comm_rank(MPI_COMM_WORLD,&rank); 
MPI_Get_processor_name(processor_name,&namelen); 
    while (!done) { 
    if (rank == 0) { 
        printf("Enter the height/width of the matrix\n");
        scanf("%d",&rows);
        scanf("%d",&cols);
        startwtime = MPI_Wtime(); 
    }
    if (rows == 0 || cols == 0) {
        done = 1; 
    } else { 
        int **arr = (int **) malloc(rows * sizeof(int*));    //creating 2d array
            for (i = 0; i < rows; i++) {
                arr[i] = (int *) malloc(cols * sizeof(int));
        }
        for (i = 0; i < rows; i++) {         //Array filling
            for (j = 0; j < cols; j++) {
                arr[i][j] = rand();
            }
        }
        for (i = 0; i < rows; i++) {      // output of the array to the screen for clarity
            for (j = 0; j < cols; j++) {
                printf("%d\n",arr[i][j]);
            }
        }
        min = arr[0][0];                                      
        for (i = 0; i < rows; i++) {                              //find min value
            for (j = 0; j < cols; j++) {                          //
                if(min > arr[i][j]){min = arr[i][j];}         //need to parallize
            }
        }    
        if (rank == 0) { 
            endwtime = MPI_Wtime();
            printf("min = %d\n", min); 
            printf("wall clock time = %f\n", endwtime-startwtime); 
            fflush( stdout ); 
            for(i = 0; i < rows; i++) {
                    free(arr[i]);
            }
            free(arr);
        }
    }
}
MPI_Finalize();
return 0;
}

对不起,我的英语不好 希望得到您的帮助

UPD:添加了类似的功能,但是程序会产生垃圾。在我看来,这是由于创建了基于指针的数组。而且很可能我滥用了功能

        MPI_Scatter (&arr[0][0], rows*cols/numprocs, MPI_INT, &arr[rows][cols], rows*cols/numprocs, MPI_INT, 0, MPI_COMM_WORLD);    
        min = arr[0][0];
        for (i = 0; i < rows; i++) {
            for (j = 0; j < cols; j++) {
                min = arr[i][j];
            }
        }   
        MPI_Reduce(&min, &value, rows*cols/numprocs, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD); 

0 个答案:

没有答案
相关问题