🐛 Changed my Pi solution to only use #pragma omp for and not already the reduction sum

main
Isabell Pflug 9 months ago
parent 15afe5e5ba
commit 6103f95445

@ -1,6 +1,7 @@
#include <iomanip> #include <iomanip>
#include <iostream> #include <iostream>
#include <omp.h> #include <omp.h>
#include <vector>
using namespace std; using namespace std;
@ -9,15 +10,28 @@ int main() {
double width = 1.0 / double(num_steps); // width of a rectangle double width = 1.0 / double(num_steps); // width of a rectangle
double sum = 0.0; // for summing up all heights of rectangles double sum = 0.0; // for summing up all heights of rectangles
int max_threads = omp_get_max_threads();
vector<double> thread_sums(max_threads, 0.0); // one sum per thread
double start_time = omp_get_wtime(); // wall clock time in seconds double start_time = omp_get_wtime(); // wall clock time in seconds
#pragma omp parallel for reduction(+:sum) #pragma omp parallel
for (int i = 0; i < num_steps; i++) { {
double x = (i + 0.5) * width; // midpoint int thread = omp_get_thread_num();
sum = sum + (1.0 / (1.0 + x * x)); // add new height of a rectangle
#pragma omp for
for (int i = 0; i < num_steps; i++) {
double x = (i + 0.5) * width; // midpoint
thread_sums[thread] += (1.0 / (1.0 + x * x)); // add new height of a rectangle
}
} }
for (int i = 0; i < max_threads; i++) {
sum+= thread_sums[i];
}
double pi = sum * 4 * width; // compute pi double pi = sum * 4 * width; // compute pi
double run_time = omp_get_wtime() - start_time; double run_time = omp_get_wtime() - start_time;
cout << "pi with " << num_steps << " steps is " << setprecision(17) cout << "pi with " << num_steps << " steps is " << setprecision(17)
<< pi << " in " << setprecision(6) << run_time << " seconds\n"; << pi << " in " << setprecision(6) << run_time << " seconds\n";
} }

Loading…
Cancel
Save