package mpi; import be.ac.vub.ir.util.Chrono; import be.ac.vub.ir.util.GetOpt; /** * @author Sarah ElShal * Parallel and sequential implementation of a prime number counter * */ public class CountPrimesCollectiveComm { // Default program parameters final static int DEFAULTSIZE = 50000; public static void main(String[] args){ // *** INITIALIZE *** GetOpt options = new GetOpt("n:",args); // allows you to parse program options. // ':' means that an argument is following after the option (here: -n 1000) String ns = options.getOptionParam('n'); int arraySize = (ns != null) ? Integer.parseInt(ns) : DEFAULTSIZE ; // ** Start up ** MPI.Init(args); int myRank = MPI.COMM_WORLD.Rank(); int nbrProcesses = MPI.COMM_WORLD.Size(); int[] data = new int [arraySize]; // in this MPI implementation, also slaves should allocate memory! This strange, because they do not send anything if (myRank == 0){ data = createAndFillArray(arraySize); // only master knows the data } // *** PARALLEL RUN *** Chrono masterChrono = new Chrono(); int nbrPrimesPar = countPrimesPar(data, args); long mastertime = masterChrono.stop(); if (myRank == 0){ System.out.println("Parallel solution found "+nbrPrimesPar+" primes among "+data.length+" odd numbers in "+masterChrono); // *** SEQUENTIAL RUN (master only) *** Chrono seqChrono = new Chrono(); int nbrPrimesSeq = countPrimes(data); long seqtime = seqChrono.stop(); if (nbrPrimesSeq == nbrPrimesPar) System.out.println("Sequential solution found the same number of primes. OK."); else System.err.println("Sequential solution found "+nbrPrimesSeq+" primes which is different!!!!!"); System.out.println(); System.out.println("PARALLEL RUNTIME = "+masterChrono); System.out.println("SEQUENTIAL RUNTIME = "+seqChrono); System.out.println("speedup = "+((float) seqtime/mastertime)); System.out.println("efficiency = "+((float) seqtime/mastertime/nbrProcesses)); System.out.println(" ++++++++++ finished +++++++++++ "); } // ** Finalize ** MPI.Finalize(); // Don't forget!! } // *** Array Filling *** static int[] createAndFillArray(int n){ // fills with all odd numbers int[] data = new int[n]; for (int i=0;i