gpt4 book ai didi

c++ - 顺序比多线程快 - OpenMp - C++

转载 作者:太空宇宙 更新时间:2023-11-04 11:53:25 26 4
gpt4 key购买 nike

我正在使用 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 编译器

最佳答案

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

diff / (float) (CLOCKS_PER_SEC * nthreads)

这只是一个近似值(并不总是正确的)。
CLOCKS_PER_SEC 代表所有内核的时钟总和...
你最好使用 OpenMP 特殊函数...

关于c++ - 顺序比多线程快 - OpenMp - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17137796/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com