title: OpenMP and C parallel for loop: why does my code slow down when using OpenMP?
body: <p>I'm new here and a beginner level programmer in C. I'm having some problem with using openmp to speedup the for-loop. Below is simple example:</p>
  
  <pre><code>#include &lt;stdlib.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;gsl/gsl_rng.h&gt;
  #include &lt;omp.h&gt;
  
  gsl_rng *rng;
  
  main()
  {
  int i, M=100000000;
  double tmp;
  
  /* initialize RNG */
  gsl_rng_env_setup();
  rng = gsl_rng_alloc (gsl_rng_taus);
  gsl_rng_set (rng,(unsigned long int)791526599);
  
  // option 1: parallel        
    #pragma omp parallel for default(shared) private( i, tmp ) schedule(dynamic)
    for(i=0;i&lt;=M-1;i++){
       tmp=gsl_ran_gamma_mt(rng, 4, 1./3 );
    }
  
  
  // option 2: sequential       
    for(i=0;i&lt;=M-1;i++){
       tmp=gsl_ran_gamma_mt(rng, 4, 1./3 );
    }
  }
  </code></pre>
  
  <p>The code draws from a gamma random distribution for M iterations. It turns out the parallel approach with openmp (option 1) takes about 1 minute while the sequential approach (option 2) takes only 20 seconds. While running with openmp, I can see the cpu usage is 800% ( the server I'm using has 8 CPUs ). And the system is linux with GCC 4.1.3. The compile command I'm using is gcc -fopenmp -lgsl -lgslcblas -lm (I'm using GSL )</p>
  
  <p>Am I doing something wrong? Please help me! Thanks!</p>
  
  <p>P.S. As pointed out by some users, it might be caused by rng. But even if I replace</p>
  
  <pre><code>tmp=gsl_ran_gamma_mt(rng, 4, 1./3 );
  </code></pre>
  
  <p>by say</p>
  
  <pre><code>tmp=1000*10000;
  </code></pre>
  
  <p>the problem still there...</p>