0

I try to use openmp parallelize my code. However, the code did't speed up. And it was 10 times slower.

code:

    N=10000;
    int i, count=0,d;
    double x, y;  

#pragma omp parallel for shared(N) private(i,x,y) reduction(+:count)   
    for( i = 0; i < N; i++ ){
        x = rand()/((double)RAND_MAX+1);
        y = rand()/((double)RAND_MAX+1);

        if(x*x + y*y < 1){
        ++count;
        }
    }

double pi= 4.0 * count / N;

I think it was because of the if statement? thanks for any help!!

Andrew
  • 11
  • 1
  • 2
    I don't think the `if` is the reason. Rather, 1) we don't know how you timed the program, which CPU you are running on, and with how many threads, 2) rand() may behave poorly in multithread, and 3) 10000 iterations is very small and you may just be observing the OpenMP overheads. – PierU Oct 23 '22 at 08:44
  • 3
    `rand()` uses a hidden state (seed) that is modified on each call, which causes a data race (i.e incorrect random number distribution and poor performance.) If you use a threadsafe random number generator instead of `rand()`, use a bigger `N` (e.g. 1000000), and properly measure the runtime, you will see a significant speed-up. – Laci Oct 23 '22 at 11:23
  • 1
    Does this answer your question? [How to generate random numbers in parallel?](https://stackoverflow.com/questions/4287531/how-to-generate-random-numbers-in-parallel) – Jérôme Richard Oct 23 '22 at 15:12
  • 1
    Thank you all !! It's because rand(). – Andrew Oct 28 '22 at 09:43

0 Answers0