OpenMP is slower than sequential

When I try the following code

double start = omp_get_wtime(); long i; #pragma omp parallel for for (i = 0; i <= 1000000000; i++) { double x = rand(); } double end = omp_get_wtime(); printf("%f\n", end - start); 

The run time is about 168 seconds, and the serial version is only 20 seconds.

I am still new to parallel programming. How can I get a parallel version that is faster than a serial version?

+7
source share
1 answer

The random rand(3) random) number generator rand(3) uses global state variables (hidden in the (g) libc implementation). Accessing them from multiple threads leads to cache problems and is not thread safe. You should use the rand_r(3) call with the seed parameter private to the stream:

 long i; unsigned seed; #pragma omp parallel private(seed) { // Initialise the random number generator with different seed in each thread // The following constants are chosen arbitrarily... use something more sensible seed = 25234 + 17*omp_get_thread_num(); #pragma omp for for (i = 0; i <= 1000000000; i++) { double x = rand_r(&seed); } } 

Please note that in parallel execution, a different stream of random numbers will be generated than when executed in sequential order. I would also recommend erand48(3) as the best (pseudo) random source number.

+13
source

All Articles