Home > Mobile >  OpenMP don't give right result and different time
OpenMP don't give right result and different time

Time:12-21

I am new to openmp and now I'm studying the usage of atomic
I had a different result and time each run.Sometimes about a minute sometimes about 19 seconds
Code:

#include <iostream>
#include<iomanip>
#include<cmath>
#include<omp.h>
#include"KiTimer.h"
int main() {
    using namespace std;
    const int NUM_REPEAT = 100000000;
    KiTimer timer;
    timer.MakeTimer(0, "足し上げ");
    timer.Start();

    double sum = 0., x = 0.;
#pragma omp parallel
    {
#pragma omp single
        cout << "Thread num:" << omp_get_num_threads() << endl;
#pragma omp for private(x)
        for (int i = 0; i < NUM_REPEAT; i  ) {
            x = sqrt(i);
#pragma omp atomic
            sum  = x;
        }
    }
    cout << setprecision(20) << "total:" << sum << endl;
    timer.Stop();
    timer.Print();
    return 0;
}

Result:
result1

result2

result3

CodePudding user response:

It's normal to get different results over time when working between threads, as you're not working in a completely isolated environment and are not developing code on the real-time operating system. This shouldn't be a bug or a question. Even in hard-time real-time operating systems, the system's response to an event can vary within a few microseconds.

CodePudding user response:

The correct way of doing sum with OMP is:

#pragma omp parallel reduction( :sum)

instead of

#pragma omp parallel
...
#pragma omp atomic

The atomic clause as far as I remember adds a big overhead when executed too often (as it is the case).

Also, the scope of x can be greatly reduced, simplifying the code: no need to use private.

About the different result, that is normal since you are adding floating point numbers in different orders in different executions. It is more of a problem when operating big numbers with small numbers since they need to be normalized when operating and will loose precision. In the case of doubles, the precision is 15 digits, so if you add 1000000000000000 1, the result will still be 1000000000000000, even if you do it many times.

  • Related