Sequential比Multi thread更快 - OpenMp - C ++

时间:2013-06-16 21:15:40

标签: c++ osx-mountain-lion openmp

我正在使用C ++& OpenMP来并行化算法以找到凸包。 但我无法获得预期的加速。实际上,顺序算法更快。 输入&输出点集存储在数组中。

您能否查看代码并让我知道更正?

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;
}

///////////在这些机器上测试/////

顺序时间:0.016466 使用两个线程:0.022979 使用四个线程:0.035213 使用8个线程:0.03315

使用的机器:Mac Book Pro 处理器:2.5 GHz Intel Core i5(至少4个逻辑核心) 内存:4GB 1600 MHz 编译器:Mac OSX编译器

1 个答案:

答案 0 :(得分:1)

问题在于你计算时间的方式。实际上,你可以这样写:

diff / (float) (CLOCKS_PER_SEC * nthreads)

这只是一个近似值(并非总是如此) CLOCKS_PER_SEC代表所有核心的时钟总和...
 你最好使用OpenMP特殊功能......

相关问题