// // Program for parallel bucket sort. // // Generates a sequence of random numbers, sorts them, and // checks the result (to confirm that the sort worked). // Prints timing results. // // Usage: bsort N // where N is how many numbers to generate and sort // #include #include // has exit(), EXIT_*, etc. #include // has STL sort(), copy() #include // has STL inner_product #include // has STL logical_and, equal_to #include "mpi++.h" // Function declarations. bool checkSort(const int N, int numsIn[], const int numsOut[]); void masterProcess(const int myID, const int nprocs, const int N, const int minVal, const int maxVal, const int numsIn[], int numsOut[]); void slaveProcess(const int myID, const int nprocs, const int N); // Main program. int main(int argc, char * argv[]) { MPI::Init(argc, argv); int nprocs = MPI::COMM_WORLD.Get_size(); int myID = MPI::COMM_WORLD.Get_rank(); if (argc < 2) { if (myID == 0) cerr << "Usage: bsort N\n"; MPI::Finalize(); exit(EXIT_FAILURE); } int N = atoi(argv[1]); // process 0 handles generating the numbers, timing the sort, // and checking the result. // it may also participate in the sort. if (myID == 0) { cout << "sorting " << N << " numbers using " << nprocs << " processes\n"; int * numsIn = new int[N]; int * numsOut = new int[N]; // generate N random numbers and record min, max values int minVal = 0; int maxVal = RAND_MAX; for (int i = 0; i < N; ++i) numsIn[i] = rand(); double start_time = MPI::Wtime(); masterProcess(myID, nprocs, N, minVal, maxVal, numsIn, numsOut); double end_time = MPI::Wtime(); cout << "time to sort numbers = " << end_time - start_time << endl; // check results (by sorting numsIn and comparing with numsOut // -- yes, very inefficient, but confirms that your sort // actually works, and we've already recorded timing info if (checkSort(N, numsIn, numsOut)) cout << "sort check completed successfully\n"; else cout << "WARNING: sort check failed\n"; } else slaveProcess(myID, nprocs, N); MPI::Finalize(); return EXIT_SUCCESS; } // Function definitions. // Verify that numsOut is the result of sorting numsIn. // Pre: numsIn, numsOut are arrays of size N. // Post: returns true if numsOut = sorted version of numsIn, // false otherwise. // modifies numsIn. // (Yes, this is ridiculously inefficient, but it does truly // confirm that the sort did what it was supposed to do.) bool checkSort(const int N, int numsIn[], const int numsOut[]) { // sort input numbers using STL sort (which presumably works) sort(numsIn, numsIn+N); // use more STL functions to compare results: // compute ((nums[0] == numsOut[0]) && (numsIn[1] == numsOut[1]) // && .... (numsIn[N-1] == numsOut[N-1]) return inner_product(numsIn, numsIn+N, numsOut, true, logical_and(), equal_to()); } // Definitions of masterProcess, slaveProcess go in this file. #include "masterslave.cc"