Meetings/Parallel

Parallel Meeting

Milad's slides on parallel computing are available here, and his example source code is included below:

#include <iostream>
#include <cmath>
#include <cstdlib>
#include "mpi.h"
#include <iomanip>

using namespace std;


// Function to return a random number between 0 and 1:
double random_number()
{
  return static_cast<double>(rand())/RAND_MAX;
}


// Define the function that we will integrate over:
double f(double x)
{
  return x*x;
}



int main()
{

  // Every MPI program begins with a call to this function:
  MPI::Init();

  // Get the total number of processes:
  int size = MPI::COMM_WORLD.Get_size();
  
  // Get my "rank", i.e. my process number:
  int rank = MPI::COMM_WORLD.Get_rank();

  // Seed the random number generator:
  srand(rank*1000);

  // Total number of points:
  const int TOTAL_POINTS = 300000000;

  // Number of points each process will pick:
  const int points_per_proc = TOTAL_POINTS/size + 1;

  double x, y; // Coordinate of our random point
  int mycount = 0; // Number of random points under the curve

  // Get the starting time so we can see how long our program takes to
  // run:
  double start_time = MPI::Wtime(); 

  for(int i = 0; i < points_per_proc; i++) {
    
    // Pick a random point:
    x = random_number();
    y = random_number();
    
    // Determine if it is under the function:
    if(y < f(x))
      mycount = mycount + 1; // Point is under function, count it.
  }

  // Done picking random points. At this point each process has to
  // send its "count" variable to the master process to be summed
  // up. MPI has a message, called Reduce, just for this purpose:
  int count;
  MPI::COMM_WORLD.Reduce(&mycount, &count, 1, MPI::INT, MPI::SUM, 0);

  // Get the ending time. Notice that the timing functions are built
  // into MPI. MPI has a lot of functions that can be used to
  // understand the performace of the program:
  double end_time = MPI::Wtime();

  // Now, only the master prints the output:
  if(rank == 0) {
    int total_points = size * points_per_proc;
    double numeric_answer = double(count) / total_points;
    double analytic_answer = 1.0/3.0;

    cout.setf(ios::scientific);
    cout << "Total number of points: " << total_points << endl;
    cout << "The integral is:        " << numeric_answer << endl;
    cout << "The analytic answer is: " << analytic_answer << endl;
    cout << "The relative error is:  " << abs(analytic_answer - numeric_answer)/analytic_answer << endl;
    cout << "The program took " << end_time - start_time << " seconds to run.\n";
    
  }

  // Make sure to call Finalize before you quit. This lets MPI know
  // we're done
  MPI::Finalize();
  return 0;
}

Attachments