p_thread c++的性能提升可以忽略不计
Negligible Perfomance Boost from p_thread c++
我一直在使用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个元素时,你的大部分性能将在函数调用中提高。粗化步骤必须通过更简单的排序、插入排序或排序网络来完成。
除非你有足够大的排序,否则实际的时间可能会淹没在测量不确定性中。
相关文章:
- 在std::thread中,joinable()然后join()线程安全吗
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 分离一个静态常量 std::thread?
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何从 std::thread 返回值
- 在C++中使用并行化的预期速度是多少(不是 OpenMp,而是 <thread>)
- 将 std::thread by 值推送到列表中
- 转发变量参数列表以模拟 std::thread
- 嵌入式设备 -> std::thread -> FreeRTOS?
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 如何防止 std::thread 在 QT 中冻结 GUI?
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- C++ - Thread Pool
- 为什么参数在构造 std::thread 时移动两次
- std::thread::_Invoker 使用线程编程时出错
- 在线程 A 中创建一个 std::thread 对象,在线程 B 中连接
- 为什么编译器抱怨 std::thread 参数在转换为右值后必须是可调用的?