p_thread c++的性能提升可以忽略不计

Negligible Perfomance Boost from p_thread c++

本文关键字:thread c++ 性能      更新时间:2023-10-16

我一直在使用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也对不能码垛的部分代码进行计数,记住Amdahl定律。

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

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