// // Program to compute the variance of a set of numbers. // // Command-line arguments are: // number of threads (P) -- required; number of threads to use // number of numbers (N) -- optional; see below // // If only one command-line argument is given, the program reads // input numbers (floating-point okay) from standard input until // end-of-file is reached. // If two command-line arguments are given, the program generates // N random numbers to use as input. // // Program output: // computed variance // elapsed time needed for computation, starting when all the // input numbers have been read in / generated, and ending // when the variance has been computed. // #include #include // has setprecision() #include // has exit(), etc. #include #include // has generate() #include // has accumulate() #include "timer.h" // has timer() // Function declarations; see definitions below for comments. double * getStdinInput(int & count); double * getRandomInput(const char inCount[], int & count); // ---- Main program ------------------------------------------------- int main(int argc, char* argv[]) { int P; // number of threads int N; // number of input numbers double * nums; // will point to array of input numbers if (argc < 2) { cerr << "Usage: " << argv[0] << " numThreads [numNumbers]\n"; exit(EXIT_FAILURE); } P = atoi(argv[1]); // Read/generate input. if (argc == 2) nums = getStdinInput(N); else nums = getRandomInput(argv[2], N); // Print some useful info. cout << "Computing the variance of " << N << " numbers using " << P << " threads\n"; // Start timing. double startTime = timer(); // Compute variance. // ==== START OF CODE TO REPLACE ==== double avg = (accumulate(nums, nums+N, 0.0))/double(N); #ifdef DEBUG cerr << "Average = " << avg << endl; #endif double variance = 0.0; for (int i = 0; i < N; ++i) variance += (nums[i] - avg)*(nums[i] - avg); // ==== END OF CODE TO REPLACE ==== // Stop timing. double endTime = timer(); // Print results. cout << "Variance times number of points = " << variance << endl; cout << "Time to compute (seconds) = " << setprecision(4) << endTime - startTime << endl; return EXIT_SUCCESS; } // ---- Function definitions ----------------------------------------- // Function to get input from standard input. double * getStdinInput(int & count) { double temp; vector vTemp; while (cin >> temp) vTemp.push_back(temp); count = vTemp.size(); double * numsToReturn = new double[count]; copy(vTemp.begin(), vTemp.end(), numsToReturn); return numsToReturn; } // Function to generate input randomly. double * getRandomInput(const char inCount[], int & count) { count = 0; count = atoi(inCount); if (count <= 0) { cerr << "Count is not numeric\n"; exit(EXIT_FAILURE); } double * numsToReturn = new double[count]; for (int i = 0; i < count; ++i) numsToReturn[i] = (double) rand() / (double) (RAND_MAX); return numsToReturn; }