package be.ac.vub.ir.mpi; import mpi.MPI; class MPIBarrierWithReduction { final static int NUMBEROFRUNS = 10; static float average(int[] data) { float sum = 0; for (int element : data) { sum += element; } return sum / data.length; } public static void main(String[] args) { int[] allData; int[] theSum; int[] privateData = new int[1]; MPI.Init(args); int PROCESSCOUNT = MPI.COMM_WORLD.Size(); int rank = MPI.COMM_WORLD.Rank(); if (rank == 0) { theSum = new int[1]; allData = new int[PROCESSCOUNT]; } else { theSum = new int[1]; allData = null; } MPI.COMM_WORLD.Scatter(allData, rank, 1, MPI.INT, privateData, 0, 1, MPI.INT, 0); for (int i = 0; i < NUMBEROFRUNS; ++i) { privateData[0] = i * rank; /* //Using Gather MPI.COMM_WORLD.Gather(privateData, 0, 1, MPI.INT, allData, rank, 1, MPI.INT, 0); if (rank == 0) { System.out.println("Average at run " + i + ":" + average(allData)); } */ // using Reduce MPI.COMM_WORLD.Reduce(privateData, 0, theSum, 0, 1, MPI.INT, MPI.SUM, 0); if (rank == 0) { float avg = (float) ((float)theSum[0] / PROCESSCOUNT); System.out.println("Average at run " + i + ":" + avg); } } MPI.Finalize(); } }