betoesquivel

Testing Cluster with PI in PIs

Oct 26th, 2015
399
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. Parallel PI computation using Collective Communication Operations (CCO)
  4. within Python objects exposing memory buffers (requires NumPy).
  5.  
  6. usage::
  7.  
  8.  $ mpiexec -n <nprocs> python cpi-buf.py
  9. """
  10.  
  11. from mpi4py import MPI
  12. from math   import pi as PI
  13. from numpy  import array
  14.  
  15. def get_n():
  16.     prompt  = "Enter the number of intervals: (0 quits) "
  17.     try:
  18.         n = 50000
  19.         if n < 0: n = 0
  20.     except:
  21.         n = 0
  22.     return n
  23.  
  24. def comp_pi(n, myrank=0, nprocs=1):
  25.     h = 1.0 / n
  26.     s = 0.0
  27.     for i in range(myrank + 1, n + 1, nprocs):
  28.         x = h * (i - 0.5)
  29.         s += 4.0 / (1.0 + x**2)
  30.     return s * h
  31.  
  32. def prn_pi(pi, PI):
  33.     message = "pi is approximately %.16f, error is %.16f"
  34.     print  (message % (pi, abs(pi - PI)))
  35.  
  36. comm = MPI.COMM_WORLD
  37. nprocs = comm.Get_size()
  38. myrank = comm.Get_rank()
  39.  
  40. n    = array(0, dtype=int)
  41. pi   = array(0, dtype=float)
  42. mypi = array(0, dtype=float)
  43.  
  44. if myrank == 0:
  45.     _n = get_n()
  46.     n.fill(_n)
  47. comm.Bcast([n, MPI.INT], root=0)
  48.  
  49. _mypi = comp_pi(n, myrank, nprocs)
  50. mypi.fill(_mypi)
  51. comm.Reduce([mypi, MPI.DOUBLE], [pi, MPI.DOUBLE],
  52.             op=MPI.SUM, root=0)
  53. if myrank == 0:
  54.     prn_pi(pi, PI)
Advertisement
Add Comment
Please, Sign In to add comment