Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <cstdlib>
  4. #include <mpi.h>
  5. #include <unistd.h>
  6.  
  7. /*
  8. Estimate pi by Monte Carlo integration of
  9. pi/4 = \int_{0}^{1} = \frac{1}{1 + x^2}.
  10.  
  11. Example from:
  12. Pitt-Francis and Whiteley, Guide to Scientific Computing in C++, Springer 2012, ch.11
  13.  
  14. $ mpic++ -o integrate.out integrate.cpp
  15.  
  16.  
  17. Result on my laptop.
  18.  
  19. Speedup = T_1 / T_p = [1, 1.751, 1.880, 2.171]
  20. Efficiency = Speedup / p = [1, 0.876, 0.627, 0.543]
  21.  
  22.  
  23. $ time mpirun -np 1 ./integrate.out
  24. pi is approximated as 3.141582652!
  25.  
  26. real 0m4.107s
  27. user 0m3.925s
  28. sys 0m0.062s
  29.  
  30. $ time mpirun -np 2 ./integrate.out
  31. pi is approximated as 3.141439028!
  32.  
  33. real 0m2.345s
  34. user 0m4.302s
  35. sys 0m0.067s
  36.  
  37. $ time mpirun -np 3 ./integrate.out
  38. pi is approximated as 3.141557082!
  39.  
  40. real 0m2.185s
  41. user 0m5.446s
  42. sys 0m0.086s
  43.  
  44. $ time mpirun -np 4 ./integrate.out
  45. pi is approximated as 3.1416283!
  46.  
  47. real 0m1.892s
  48. user 0m6.557s
  49. sys 0m0.136s
  50.  
  51. */
  52.  
  53.  
  54. int main(int argc, char* argv[]) {
  55.  
  56. MPI::Init(argc, argv);
  57. int num_procs = MPI::COMM_WORLD.Get_size();
  58. int rank = MPI::COMM_WORLD.Get_rank();
  59.  
  60. // set seed, make sure each process uses different one
  61. srand(getpid());
  62. long long total_n = 100000000;
  63. double sum = 0;
  64.  
  65. for (long long i=0; i<total_n/num_procs; i++) {
  66. // generate from uniform on [0, 1]
  67. double x = rand() / (double)RAND_MAX;
  68. double f = 1.0 / (1 + x * x);
  69. sum += (f / total_n);
  70. }
  71.  
  72. double result;
  73. MPI::COMM_WORLD.Reduce(&sum, &result, 1, MPI::DOUBLE, MPI::SUM, 0);
  74. MPI::Finalize();
  75.  
  76. if (rank == 0) {
  77. std::cout << std::setprecision(10) <<
  78. "pi is approximated as " << 4.0*result << "!\n";
  79. }
  80.  
  81.  
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement