简体   繁体   中英

Sequential is faster than Multi threaded - OpenMp - C++

I am using C++ & OpenMP to parallelize an algorithm to find the convex hull. But I am not able to get the expected speedup. In fact, the sequential algorithm is faster. The input & output set of points are stored in arrays.

Could you please look into the code and let me know the corrections?

Point *points = new Point[inp_size]; // contains the input
  int th_id;

  omp_set_num_threads(nthreads);
  clock_t t1,t2;
      t1=clock();
  #pragma omp parallel private(th_id)
  {
    th_id = omp_get_thread_num();
///////////// …. Only Function called ….///////////////////////////////////
    findParallelUCHWOUP(points,th_id+1, nthreads, inp_size);

  }
  t2=clock();
  float diff ((float)t2-(float)t1);
  float seconds = diff / CLOCKS_PER_SEC;
  std::cout << "Time Elapsed in seconds:" << seconds << '\n';

///////////////////////////////////////////////////////////////

int findParallelUCHWOUP(Point iv[],int id, int thread_num, int inp_size){

    int numElems = inp_size/thread_num;
        int first = (id-1) * numElems;;
        int last;
        if(id == thread_num){
            last = inp_size-1;
        }
        else{
            last = id*numElems-1;
        }

        output[first]=iv[first];
          std::stack<int> s;
          s.push(first);
          int i=first+1;
        while(i<last){
            if ( crossProduct(iv, i, first, last) > 0){
                s.push(i);
                i++;
                break;
            }else{
                i++;
            }
        }

        if(i==last){
            s.push(last);
            return 0;
        }

        for(;i<=last;i++){
            if ( crossProduct(iv, i, first, last) >= 0){
                  while ( s.size()>1 && crossProduct(iv, s.top(), second(s), i) <= 0){
                      s.pop();
                  }
                  s.push(i);
            }

        }
          int count=s.size();
          sizes[id-1] = count;
          while(!s.empty()){
              output[first+count-1]=iv[s.top()];
              s.pop();
              count--;
          }

    return 0;
}

///////////tested on these machines/////

Sequential Time:0.016466 Using two threads:0.022979 Using four threads:0.035213 Using 8 threads: 0.03315

Machine used: Mac Book Pro Processor: 2.5 GHz Intel Core i5(at least 4 logical cores) Memory: 4GB 1600 MHz Compiler: Mac OSX Compiler

The problem is the way you count time. Actually, you could write something like:

diff / (float) (CLOCKS_PER_SEC * nthreads)

And this is only an approximation (and not always true).
CLOCKS_PER_SEC stands for sum of clocks of all cores...
You'd better use OpenMP special functions...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM