gpt4 book ai didi

c++ - pthread c++ 的性能提升可忽略不计

转载 作者:行者123 更新时间:2023-11-28 06:00:50 25 4
gpt4 key购买 nike

我一直在使用 Mac OS gcc 4.2.1 和 Eclipse 编写一个程序,使用简单的合并排序对数字进行排序。我已经广泛测试了这种排序,我知道它是有效的,我想,也许有点天真,因为算法划分列表的方式,我可以简单地让线程排序一半,主线程排序一半,然后这将花费一半的时间,但不幸的是,它似乎没有用。

主要代码如下:

    float x = clock(); //timing
int half = (int)size/2; // size is the length of the list

status = pthread_create(thready,NULL,voidSort,(void *)datay); //start the thread sorting

sortStep(testArray,tempList,half,0,half); //sort using the main thread

int join = pthread_join(*thready,&someptr); //wait for the thread to finish

mergeStep(testArray,tempList,0,half,half-1); //merge the two sublists

if (status != 0) { std::cout << "Could not create thread.\nError: " << status << "\n"; }

if (join != 0) { std::cout << "Could not create thread.\nError: " << status << "\n"; }

float y = clock() - x; //timing

sortStep 是主要的排序函数,mergeStep 用于合并一个数组中的两个子列表(它使用占位符数组来切换数字),而 voidSort 是我用来将包含 sortStep 的所有参数的结构传递给线程的函数。我觉得也许主线程正在等待新线程完成,但我不确定如何克服它。我非常非常感谢您提供的所有帮助,在此先感谢您!

编辑:这是合并步骤

void mergeStep (int *array,int *tempList,int start, int lengthOne, int lengthTwo) //the merge step of a merge sort
{
int i = start;
int j = i+lengthOne;
int k = 0; // index for the entire templist

while (k < lengthOne+lengthTwo) // a C++ while loop
{
if (i - start == lengthOne)
{ //list one exhausted
for (int n = 0; n+j < lengthTwo+lengthOne+start;n++ ) //add the rest
{
tempList[k++] = array[j+n];
}
break;
}

if (j-(lengthOne+lengthTwo)-start == 0)
{//list two exhausted
for (int n = i; n < start+lengthOne;n++ ) //add the rest
{
tempList[k++] = array[n];
}
break;
}

if (array[i] > array[j]) // figure out which variable should go first
{
tempList[k] = array[j++];
}

else
{
tempList[k] = array[i++];
}
k++;
}

for (int s = 0; s < lengthOne+lengthTwo;s++) // add the templist into the original
{
array[start+s] = tempList[s];
}
}

-将

最佳答案

创建线程的开销相当大,所以除非你有大量(待定)数据需要排序,否则最好在主线程中排序。

mergeStep 也计入不能 palletized 的代码部分,记住 Amdahl's law .

如果您在 sortStep 的最后一部分没有粗化步骤,当您得到低于 8-16 个元素时,您的大部分性能将在函数调用中提高。粗化步骤必须通过更简单的排序、插入排序或排序网络来完成。

除非您有足够大的排序,否则实际时间可能会淹没在测量不确定性中。

关于c++ - pthread c++ 的性能提升可忽略不计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324078/

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