为什么OpenMP的性能优于线程
Why is OpenMP outperforming threads?
我一直在OpenMP 中调用这个
#pragma omp parallel for num_threads(totalThreads)
for(unsigned i=0; i<totalThreads; i++)
{
workOnTheseEdges(startIndex[i], endIndex[i]);
}
在C++11中,std::threads(我相信这些只是pthread)
vector<thread> threads;
for(unsigned i=0; i<totalThreads; i++)
{
threads.push_back(thread(workOnTheseEdges,startIndex[i], endIndex[i]));
}
for (auto& thread : threads)
{
thread.join();
}
但是,OpenMP的实现速度是原来的两倍--更快!我本以为C++11线程会更快,因为它们更低级。注意:上面的代码在一个循环中不仅被调用一次,而且可能被调用10000次,所以这可能与此有关?
编辑:为了澄清,在实践中,我要么使用OpenMP,要么使用C++11版本,而不是两者都使用。当我使用OpenMP代码时,需要45秒,当我使用C++11时,需要100秒。
totalThreads
在您的OpenMP版本中来自哪里?我打赌它不是startIndex.size()
。
OpenMP版本将请求排队到totalThreads
工作线程上。看起来C++11版本创建了startIndex.size()
线程,如果这是一个很大的数字,那么这将涉及大量的开销。
请考虑以下代码。OpenMP版本在0秒内运行,而C++11版本在50秒内运行。这不是因为函数是doNothing,也不是因为向量在循环中。正如您所能想象的,在每次迭代中,都会创建并销毁c++11线程。另一方面,OpenMP实际上实现了线程池。它不在标准中,但在英特尔和AMD的实现中。
for(int j=1; j<100000; ++j)
{
if(algorithmToRun == 1)
{
vector<thread> threads;
for(int i=0; i<16; i++)
{
threads.push_back(thread(doNothing));
}
for(auto& thread : threads) thread.join();
}
else if(algorithmToRun == 2)
{
#pragma omp parallel for num_threads(16)
for(unsigned i=0; i<16; i++)
{
doNothing();
}
}
}
相关文章:
- C++ 多线程 - 与线程合并排序的算法替代
- 在 C++ 中扩展作业/工作线程多线程系统
- __thread Embarcadero c++ 10.1 中不创建特定于线程的变量
- 运行线程和线程对象之间的关系
- 条件_variable和unique_lock如何适用于线程安全列表
- 多线程与线程小问题
- OpenBLAS 只为一个例程设置线程数
- 多线程和单线程代码维护
- 从第二个线程访问主线程中的变量
- 加载的 OpenGL 函数是特定于上下文还是特定于线程?(视窗)
- 暂停和恢复多线程环境中另一个线程的线程C++技术建议
- 多线程 - DO线程同时开始运行
- boost::asio绞线缠绕的线程无法立即工作
- 有没有更好的方法可以使此代码线程安全?线程局部静态似乎是一个生硬的工具
- C 多线程:管理线程
- 我应该为等待工作线程的主线程使用哪种内存顺序
- 多线程程序线程联接问题
- 特定于线程的数据 - 为什么我不能只使用带有线程 ID 的静态映射?
- UnookWindowsHookEx是否从特定于线程的挂钩应用程序中卸载库
- C++中特定于线程的区域设置操作