| 1 | = Source code = |
| 2 | {{{ |
| 3 | /* Program: |
| 4 | * mpich_example 內建範例,計算 pi 。 |
| 5 | * History: |
| 6 | * 2008-04-11 BETA |
| 7 | * 2008-06-19 增加可重複輸入欲計算之精準度 |
| 8 | * 2008-06-23 加入 MPI_Barrier 以確保每個 node 在接受 n 後才執行 |
| 9 | * / |
| 10 | |
| 11 | #include "mpi.h" |
| 12 | #include <stdio.h> |
| 13 | #include <math.h> |
| 14 | #include <time.h> |
| 15 | |
| 16 | double f( double ); |
| 17 | double f( double a ) |
| 18 | { |
| 19 | return (4.0 / (1.0 + a*a)); |
| 20 | } |
| 21 | |
| 22 | int main( int argc, char *argv[]) |
| 23 | { |
| 24 | int done = 0, n, myid, numprocs, i=0; |
| 25 | double PI25DT = 3.141592653589793238462643; |
| 26 | double mypi, pi, h, sum, x; |
| 27 | double startwtime = 0.0, endwtime; |
| 28 | int namelen; |
| 29 | char processor_name[MPI_MAX_PROCESSOR_NAME]; |
| 30 | MPI_Init(&argc,&argv); |
| 31 | MPI_Comm_size(MPI_COMM_WORLD,&numprocs); |
| 32 | MPI_Comm_rank(MPI_COMM_WORLD,&myid); |
| 33 | MPI_Get_processor_name(processor_name,&namelen); |
| 34 | fprintf(stderr,"Process %d on %s\n", |
| 35 | myid, processor_name); |
| 36 | n = 0; |
| 37 | while (!done) |
| 38 | { |
| 39 | /* 由 node 0 將使用者輸入的值送給其它的 node */ |
| 40 | if (myid == 0) |
| 41 | { |
| 42 | printf("Enter the number of intervals: (0 quits) "); |
| 43 | scanf("%d", &n); |
| 44 | startwtime = MPI_Wtime(); |
| 45 | } |
| 46 | |
| 47 | /* 這非常重要,所有的 node 必需在此同步,才可以收到使用者輸入的 n */ |
| 48 | MPI_Barrier(MPI_COMM_WORLD); |
| 49 | |
| 50 | /* 將 n 送給其它的 node */ |
| 51 | MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); |
| 52 | if (n == 0) |
| 53 | done = 1; |
| 54 | else |
| 55 | { |
| 56 | |
| 57 | /* 此為計算 pi 的演算法 */ |
| 58 | h = 1.0 / (double) n; |
| 59 | sum = 0.0; |
| 60 | for (i = myid + 1; i <= n; i += numprocs) |
| 61 | { |
| 62 | x = h * ((double)i - 0.5); |
| 63 | sum += f(x); |
| 64 | } |
| 65 | mypi = h * sum; |
| 66 | |
| 67 | /* 將算完的結果傳給 node 0 加總 */ |
| 68 | MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); |
| 69 | if (myid == 0) |
| 70 | { |
| 71 | printf("pi is approximately %.16f, Error is %.16f\n", |
| 72 | pi, fabs(pi - PI25DT)); |
| 73 | endwtime = MPI_Wtime(); |
| 74 | printf("wall clock time = %f\n", |
| 75 | endwtime-startwtime); |
| 76 | } |
| 77 | } |
| 78 | } |
| 79 | MPI_Finalize(); |
| 80 | return 0; |
| 81 | } |
| 82 | }}} |
| 83 | = Result = |
| 84 | [[Image(demo2-01.png)]] |