I'm learning OpenMP and have some problems: Parallel program slower than serial, i'm confusing (1 thread vs 2 threads) My code:
#include <iostream>
#include <omp.h>
using namespace std;
int main()
{
int threadsNumber=1;
int S=0;
cout << "Enter number of threads:\n";
cin >> threadsNumber;
double start, end, calculationTime;
omp_set_num_threads(threadsNumber);
start = omp_get_wtime();
#pragma omp parallel for reduction(+: S)
for(int i=1;i<1000;i++) {
S+= 10;
}
#pragma omp end parallel
end = omp_get_wtime();
calculationTime = end - start;
cout << "Время выполнения: " << calculationTime << "\n";
cout<<"S = "<< S <<"\n";
return 0;
}
Results: 1 thread: 2.59876e-05 2 threads: 0.000102043
Where my mistake? Thank you!
1000000000instead of1000. It should return 2 seconds for 1 thread and 1 second for 2 threads. If compiler optimizations are enabled then usevolatilevariables to prevent optimizing out the loop.