I have a simple question about using OpenMP (with C ++) that I was hoping someone could help me. I gave a small example below to illustrate my problem.
#include<iostream> #include<vector> #include<ctime> #include<omp.h> using namespace std; int main(){ srand(time(NULL));//Seed random number generator vector<int>v;//Create vector to hold random numbers in interval [0,9] vector<int>d(10,0);//Vector to hold counts of each integer initialized to 0 for(int i=0;i<1e9;++i) v.push_back(rand()%10);//Push back random numbers [0,9] clock_t c=clock(); #pragma omp parallel for for(int i=0;i<v.size();++i) d[v[i]]+=1;//Count number stored at v[i] cout<<"Seconds: "<<(clock()-c)/CLOCKS_PER_SEC<<endl; for(vector<int>::iterator i=d.begin();i!=d.end();++i) cout<<*i<<endl; return 0; }
In the above code, a vector v is created containing 1 billion random numbers in the range [0,9] . Then the code goes through v , counting how many instances of each different integer are (i.e., how many of them are found in v , how many are two, etc.)
Each time a certain integer occurs, it is calculated by increasing the corresponding element of the vector d . Thus, d[0] counts how many zeros, d[6] counts how many gears, and so on. Does it still make sense?
My problem is that I am trying to make the count loop parallel. Without the #pragma OpenMP instruction, my code takes 20 seconds, but with pragma it takes 60 seconds.
It is clear that I misunderstood some concept related to OpenMP (perhaps how data is shared / accessible?). Can someone explain my mistake, please, or point me towards some insightful literature with relevant keywords to help me find?
source share