Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <mpi.h>
  4.  
  5. /*
  6.  
  7. # Goal
  8.  
  9. Estimate pi using Leibniz formula:
  10. pi/4 = \sum_{n=0}^{\infty} \frac{(-1)^{n}}{sn + 1}.
  11.  
  12. Example from:
  13. Pitt-Francis and Whiteley, Guide to Scientific Computing in C++, Springer 2012, ch.11
  14.  
  15.  
  16. # Compilation
  17.  
  18. $ mpic++ -o leibniz.out leibniz.cpp
  19.  
  20.  
  21. # Execution, and expected (approximate) result.
  22.  
  23. Result of my laptop below.
  24. Since this machine has four processors, there is no gain increasing
  25. the number of proccesses to five or more.
  26.  
  27. Speedup = T_1 / T_p = [1, 1.846, 2.599, 3.313]
  28. Efficiency = Speedup / p = [1, 0.923, 0.866, 0.828]
  29.  
  30.  
  31. $ time mpirun -np 1 ./leibniz.out
  32. pi is approximated as 3.141592653!
  33.  
  34. real 0m14.397s
  35. user 0m14.222s
  36. sys 0m0.048s
  37.  
  38.  
  39. $ time mpirun -np 2 ./leibniz.out
  40. pi is approximated as 3.141592653!
  41.  
  42. real 0m7.801s
  43. user 0m15.170s
  44. sys 0m0.073s
  45.  
  46.  
  47. $ time mpirun -np 3 ./leibniz.out
  48. pi is approximated as 3.141592653!
  49.  
  50. real 0m5.539s
  51. user 0m15.671s
  52. sys 0m0.105s
  53.  
  54.  
  55. $ time mpirun -np 4 ./leibniz.out
  56. pi is approximated as 3.141592653!
  57.  
  58. real 0m4.346s
  59. user 0m15.925s
  60. sys 0m0.174s
  61.  
  62.  
  63. $ time mpirun -np 8 ./leibniz.out
  64. pi is approximated as 3.141592653!
  65.  
  66. real 0m4.411s
  67. user 0m16.172s
  68. sys 0m0.280s
  69.  
  70. */
  71.  
  72.  
  73. int main(int argc, char* argv[]) {
  74.  
  75. long long max_n = 1000000000;
  76. MPI::Init(argc, argv);
  77.  
  78. int num_procs = MPI::COMM_WORLD.Get_size();
  79. int rank = MPI::COMM_WORLD.Get_rank();
  80.  
  81. double sum = 0;
  82. for (long long n=rank; n<max_n; n+=num_procs) {
  83. double tmp = 1.0 / ( 2.0 * (double)n + 1);
  84. if (n % 2 == 0) {
  85. sum += tmp;
  86. } else {
  87. sum -= tmp;
  88. }
  89. }
  90.  
  91. double global_sum;
  92. MPI::COMM_WORLD.Reduce(&sum, &global_sum, 1, MPI::DOUBLE, MPI::SUM, 0);
  93. // 1 : count, 0: destination
  94.  
  95. if (rank == 0) {
  96. std::cout << std::setprecision(10) <<
  97. "pi is approximated as " << 4.0*global_sum << "!\n";
  98. }
  99.  
  100. MPI::Finalize();
  101. return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement