// ================================================================== // Author: Jean-Michel RICHER // Email: jean-michel.richer@univ-angers.fr // Institution: LERIA, Faculty of Science // University of Angers, France // ================================================================== #include #include using namespace std; typedef double real; /* ================================================================== * SUBPROGRAM * * real sum_reduction( real *t, int size ); * * WHAT * * Perform sum of values of the array @param(t) of * @param(size) elements * * HOW * * Simply iterate and sum each value. * * PARAMETERS * * @paramdef(real, t) : array * @paramdef(int, size) : size of the array * * ================================================================== */ real sum_reduction(real *t, int size) { real total = 0.0; for (int i = 0; i < size; ++i) { total += t[i]; } return total; } /* ================================================================== * SUBPROGRAM * * real parallel_sum_reduction( real *t, int size ); * * WHAT * * Perform sum of values of the array @param(t) of * @param(size) elements * * HOW * * Simply iterate and sum each value but use parallelism * * PARAMETERS * * @paramdef(real, t) : array * @paramdef(int, size) : size of the array * * ================================================================== */ real parallel_sum_reduction(real *t, int size) { real total = 0.0; // OpenMP directive for parallelization #pragma omp parallel for reduction(+ : total) for (int i = 0; i < size; ++i) { total += t[i]; } return total; } /* ================================================================== * SUBPROGRAM * * int main(int argc, char *argv[]) * * WHAT * * Main program that repeats 100 times the reduction and sums all * results. * Expected result is sum=10000000000.00 * * PARAMETERS * * @paramdef(int,argc) : number of command line arguments * @paramdef(char **, argv) : command line arguments as C-strings * * ================================================================== */ int main(int argc, char *argv[]) { int method = 1; if (argc > 1) { method = std::stoi(argv[1]); } // maximum number of values in the array const int MAX_VALUES = 100'000'000; // array of reals real *data; // allocate array data = new real[MAX_VALUES]; // fill array for (int i = 0; i < MAX_VALUES; ++i) { data[i] = 1.0; } real sum = 0; for (int r = 1; r <= 100; ++r) { if (method == 1) { sum += sum_reduction(data, MAX_VALUES); } else { sum += parallel_sum_reduction(data, MAX_VALUES); } } // print result cout << "sum=" << std::fixed << std::setprecision(2) << sum << endl; return EXIT_SUCCESS; }