MPI Ruby Lesson 1

February 8th, 2008

I want to start doing some parallel programming blogging, and thought I would start with a simple example of some distributed code that computes PI. Contrary to the concerns of the state of Indiana circa 1897 the value of PI is not and never will be 3.2. Having said that let's take a look at how to do this using MPI Ruby.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

PI25DT = 3.141592653589793238462643
NINTERVALS = 10000

rank = MPI::Comm::WORLD.rank()
size = MPI::Comm::WORLD.size()

startwtime = MPI.wtime()
h = 1.0 / NINTERVALS
sum = 0.0
(rank + 1).step(NINTERVALS, size) do |i|
  x = h * (i - 0.5)
  sum += (4.0 / (1.0 + x**2))
end
mypi = h * sum

pi = MPI::Comm::WORLD.reduce(mypi, MPI::Op::SUM, 0)

if rank == 0 then
  printf "pi is ~= %.16f, error = %.16f\n", pi, (pi - PI25DT).abs
  endwtime = MPI.wtime()
  puts "wallclock time = #{endwtime-startwtime}"
end
Then run the script

% mpirun -np 2 mpi_ruby pi.rb
Where -np 2 is the number of processors you would like the script to use. After running you should get an output similar to this.

pi is ~= 3.1415926544231318, error = 0.0000000008333383
wallclock time = 0.0111241340637207
This is the first of many posts that will become increasingly more useful as time goes on.

Sorry, comments are closed for this article.