265 | | int numprocs, myrank, i=0, buf; |
266 | | MPI_Status status; |
267 | | MPI_Init(&argc, &argv); |
268 | | MPI_Comm_size(MPI_COMM_WORLD, &numprocs); |
269 | | MPI_Comm_rank(MPI_COMM_WORLD, &myrank); |
270 | | |
271 | | /* 除了 Node 0 以外的所有 node 都要送 5 個訊息給 node 0 , 將 i 當成 tag 送出 */ |
272 | | if (myrank > 0) |
273 | | { |
274 | | for(i = 0; i < 5; i++) |
| 270 | return (4.0 / (1.0 + a*a)); |
| 271 | } |
| 272 | |
| 273 | int main( int argc, char *argv[]) |
| 274 | { |
| 275 | int done = 0, n, myid, numprocs, i=0; |
| 276 | double PI25DT = 3.141592653589793238462643; |
| 277 | double mypi, pi, h, sum, x; |
| 278 | double startwtime = 0.0, endwtime; |
| 279 | int namelen; |
| 280 | char processor_name[MPI_MAX_PROCESSOR_NAME]; |
| 281 | MPI_Init(&argc,&argv); |
| 282 | MPI_Comm_size(MPI_COMM_WORLD,&numprocs); |
| 283 | MPI_Comm_rank(MPI_COMM_WORLD,&myid); |
| 284 | MPI_Get_processor_name(processor_name,&namelen); |
| 285 | fprintf(stderr,"Process %d on %s\n", |
| 286 | myid, processor_name); |
| 287 | n = 0; |
| 288 | while (!done) |
276 | | buf = myrank * 100 + i; |
277 | | MPI_Send(&buf, 1, MPI_INT, 0, i, MPI_COMM_WORLD); |
| 290 | /* 由 node 0 將使用者輸入的值送給其它的 node */ |
| 291 | if (myid == 0) |
| 292 | { |
| 293 | printf("Enter the number of intervals: (0 quits) "); |
| 294 | scanf("%d", &n); |
| 295 | startwtime = MPI_Wtime(); |
| 296 | } |
| 297 | |
| 298 | /* 這非常重要,所有的 node 必需在此同步,才可以收到使用者輸入的 n */ |
| 299 | MPI_Barrier(MPI_COMM_WORLD); |
| 300 | |
| 301 | /* 將 n 送給其它的 node */ |
| 302 | MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); |
| 303 | if (n == 0) |
| 304 | done = 1; |
| 305 | else |
| 306 | { |
| 307 | |
| 308 | /* 此為計算 pi 的演算法 */ |
| 309 | h = 1.0 / (double) n; |
| 310 | sum = 0.0; |
| 311 | for (i = myid + 1; i <= n; i += numprocs) |
| 312 | { |
| 313 | x = h * ((double)i - 0.5); |
| 314 | sum += f(x); |
| 315 | } |
| 316 | mypi = h * sum; |
| 317 | |
| 318 | /* 將算完的結果傳給 node 0 加總 */ |
| 319 | MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); |
| 320 | if (myid == 0) |
| 321 | { |
| 322 | printf("pi is approximately %.16f, Error is %.16f\n", |
| 323 | pi, fabs(pi - PI25DT)); |
| 324 | endwtime = MPI_Wtime(); |
| 325 | printf("wall clock time = %f\n", |
| 326 | endwtime-startwtime); |
| 327 | } |
| 328 | } |