采用 MPI_Send 和 MPI_Recv 编写代码来实现 MPI_Allgather 的功能

MPI_Allgather实现

#include "stdio.h"
#include "mpi.h"
int main( int argc, char* argv[] )
{
    int i;
    int rank, nproc;
    int isend, irecv[32];
    double start_time, end_time, time, cputime;  
	       
    MPI_Init( &argc, &argv );
    start_time = MPI_Wtime();
	MPI_Comm_size( MPI_COMM_WORLD, &nproc );
    MPI_Comm_rank( MPI_COMM_WORLD, &rank );

    isend = rank + 1;
    MPI_Allgather(&isend, 1, MPI_INT, irecv, 1, MPI_INT,
                              MPI_COMM_WORLD);
    for(i=0; i<nproc; i++)
         printf("My rank =  %d  irecv = %d\n", rank, irecv[i]);
    
    end_time = MPI_Wtime();
    cputime = end_time - start_time;
    MPI_Reduce(&cputime,&time,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
    if(rank == 0)
    printf("time is %f s.\n",time/nproc);
    
	MPI_Finalize();    
}

采用 MPI_Send 和 MPI_Recv 编写代码来实现 

#include "time.h"
#include "stdio.h"
#include "mpi.h"
int main(int argc,char * argv[])
{
    int i;
    int rank, nproc;
    int send, recv[32];
    MPI_Status status;

    double start_time, end_time, time, cputime;       
 
    MPI_Init( &argc, &argv );
    start_time = MPI_Wtime();
    MPI_Comm_size( MPI_COMM_WORLD, &nproc );
    MPI_Comm_rank( MPI_COMM_WORLD, &rank );
   
    send = rank + 1;

    for(i=0;i<nproc;i++){
	MPI_Send(&send,1,MPI_INT,i,rank,MPI_COMM_WORLD);
    }

    for(i=0;i<nproc;i++){
	MPI_Recv(recv+i,1,MPI_INT,i,i,MPI_COMM_WORLD,&status);
    }
    
    for(i=0; i<nproc; i++)
         printf("My rank =  %d  recv = %d\n", rank, recv[i]);

    end_time = MPI_Wtime();
    cputime = end_time - start_time;
    MPI_Reduce(&cputime,&time,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);

    if(rank == 0)
    printf("time is %f s.\n",time/nproc);

    MPI_Finalize();
}



你可能感兴趣的:(采用 MPI_Send 和 MPI_Recv 编写代码来实现 MPI_Allgather 的功能)