#include "mpi.h" #include #include #include #include #include int main( int argc, char *argv[] ) { int n, myid, numprocs, i; double *A, sum0, sum, t0; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); fprintf(stderr, "Process %d/%d, pid %d.\n", myid, numprocs, getpid()); if (myid == 0) { char s[1024]; fprintf(stderr, "Press Enter ... "); fgets(s, sizeof(s), stdin); } MPI_Barrier(MPI_COMM_WORLD); if (argc != 2) { if (myid == 0) fprintf(stderr, "Usage: %s n\n", argv[0]); MPI_Finalize(); exit(1); } n = atoi(argv[1]); assert(n > 0); if ((A = malloc(n * sizeof(*A))) == NULL) { fprintf(stderr, "%d: failed allocation.\n", myid); MPI_Abort(MPI_COMM_WORLD, 1); exit(1); } /* 产生随机数据 */ srandom(getpid()); for (i = 0; i < n; i++) A[i] = random() / (double)RAND_MAX; /* 计算本地数组和 */ sum0 = 0.0; for (i = 0; i < n; i++) sum0 += A[i]; printf("Proc %d: n = %d, local sum = %g\n", myid, n, sum0); /* 开始计时 */ t0 = MPI_Wtime(); /* 计算全局和 */ MPI_Reduce(&sum0, &sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); /* 打印最终结果及通信花费的墙钟时间 */ if (myid == 0) printf("n = %d, sum = %g, time = %g (s)\n", n, sum, MPI_Wtime()-t0); MPI_Finalize(); return 0; }