Skip to content

Instantly share code, notes, and snippets.

@Gateswong
Last active August 29, 2015 14:00
Show Gist options
  • Save Gateswong/93d78e76cb9e36f57831 to your computer and use it in GitHub Desktop.
Save Gateswong/93d78e76cb9e36f57831 to your computer and use it in GitHub Desktop.
#include "MPI.h" // 扣分点!
float a[200][200], b[200][200], PROD = 1;
int myrank, numproc;
MPI_Init();
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
MPI_Comm_size(MPI_COMM_WORLD, &numproc);
// MPI-Scatter
float *ax, PRODx = 1.0;
ax = (float* )malloc(sizeof(float) * 200 * 200 / numproc);
MPI_Scatter(a, 200 * 200, MPI_FLOAT, // 假设 200/numproc 可以整除
ax, 200 * 200 / numproc, MPI_FLOAT,
0, MPI_COMM_WORLD);
MPI_Bcast(b, 200 * 200, MPI_FLOAT, 0, MPI_COMM_WORLD);
// Compute
for (i = 0; i < 200 / numproc; i ++) {
if (i == 0 && myrank == 0) { continue; } // 边界检查
for (j = 1; j < 200; j ++) {
if (j < 199) { // 边界检查
ax[i][j] = ax[i][j-1] + b[j+1][i + myrank * 200 / numproc]/2.0;
}
PRODx = PRODx * ax[i][j];
}
}
// MPI-Gather and Reduce
MPI_Gather(ax, 200 * 200 / numproc, MPI_FLOAT,
a, 200 * 200, MPI_FLOAT,
0, MPI_COMM_WORLD);
MPI_Reduce(PRODx, PROD, 1, MPI_FLOAT, MPI_PROD, 0, MPI_COMM_WORLD);
// End
MPI_Finalize();
float a[200, 200], b[200, 200], PROD;
int i, j;
for (i = 1; i < 200; i ++) {
for (j = 1; j < 199; j ++) {
a[i, j] = a[i, j-1] + b[j+1, i]/2.0;
}
}
for (i = 1; i < 200; i ++) {
for (j = 1; j < 200; j ++) {
PROD = PROD * a[i,j];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment