#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(int argc, char **argv)
{
int i, myid, other, numprocs;
double start, end;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
int N = 65535;
int *buf = (int *)malloc(sizeof(int) * (N + 1));
if (buf == NULL) printf("Not enouth memory from %d!\n", myid);
if(myid == 0)
for(i = 0; i < N; i ++ ) buf[i] = 1;
else
memset(buf, 0, sizeof(buf));
if(myid == 0) start = MPI_Wtime();
MPI_Bcast(buf, N, MPI_INT, 0, MPI_COMM_WORLD);
if(myid == 0) {
end = MPI_Wtime();
printf("Elapsed time: %f\n", end - start);
}
if(myid == 0)
for(i = 0; i < N; i ++ ) buf[i] = 1;
else
memset(buf, 0, sizeof(buf));
if(myid == 0) {
start = MPI_Wtime();
for (i = 1; i < numprocs; i++) {
MPI_Send(buf, N, MPI_INT, i, 99, MPI_COMM_WORLD);
}
end = MPI_Wtime();
printf("Elapsed time: %f\n", end - start);
}
else
MPI_Recv(buf, N, MPI_INT, 0, 99, MPI_COMM_WORLD, &status);
free(buf);
buf = NULL;
//printf("process %d freeing memory.../n",myid);
MPI_Finalize();
}
result:
[root@c0108 zlt]# mpicc comm.c -o comm
[root@c0108 zlt]# mpiexec -n 8 ./comm
Elapsed time: 0.073060
Elapsed time: 0.158653
从结果上看,MPI的广播操作应该是经过优化的。