If Clause is slow

General OpenMP discussion

If Clause is slow

Postby Daishisan » Tue Apr 03, 2012 1:05 am

Hi,

I've been experimenting with OpenMP in C++ and found some unusual behaviour. Specifically, code such as the following (this is a simplification of the code I saw this in - I don't have "if (false)" lying around in my real code):
Code: Select all
    int sum = 0;
    #pragma omp parallel for reduction(+:sum) schedule(dynamic, 4) if (false)
    for (int i = 0; i <= 100000000; ++i)
        sum += i;

runs much slower than taking the if clause out such as:
Code: Select all
    int sum = 0;
    if (false) {
        #pragma omp parallel for reduction(+:sum) schedule(dynamic, 4)
        for (int i = 0; i <= 100000000; ++i)
            sum += i;
    } else {
        for (int i = 0; i <= 100000000; ++i)
            sum += i;
    }

This seems to indicate that the OpenMP is doing other stuff that is really not necessary. I have also found that changing the scheduling parameter will have varying effects on the slow-down.

Can anyone explain why this is the case, and if there is a way to maintain the speed but not duplicate the for loop (if the if clause does not always evaluate to false)?

Thanks!
Daishisan
 
Posts: 2
Joined: Tue Apr 03, 2012 12:29 am

Re: If Clause is slow

Postby james » Wed Apr 04, 2012 8:08 pm

If you look at the specification closely you will see that the if clause does not eliminate the parallel region it simply reduces the number of threads that will execute the parallel region to one. This is to ensure that the if clause does not change the semantics of the program. Thus your code example is behaving exactly as expected. If you remove the parallel region it is going to run faster than it would if it were run on a single thread, this is because there is overhead in just starting up the parallel region no matter how many threads are involved.

You will likely find that if you use the static schedule that the if (false) version runs faster then any other schedule.

If you don't want to duplicate the loop outline it to a function and call the function in the two different places.
james
 
Posts: 53
Joined: Fri May 16, 2008 9:27 am

Re: If Clause is slow

Postby Daishisan » Sat Apr 14, 2012 2:34 am

It seems weird that this is the desired behaviour. Is it advantageous in some way for the if clause to begin the parallel overhead even if parallelization is avoided?
Daishisan
 
Posts: 2
Joined: Tue Apr 03, 2012 12:29 am


Return to Using OpenMP

Who is online

Users browsing this forum: Yahoo [Bot] and 6 guests

cron