OpenMP 不会利用所有内核?
我正在尝试使用 OpenMP 使一些代码并行。
omp_set_num_threads( 8 );
#pragma omp parallel
for (int i = 0; i < verSize; ++i)
{
#pragma omp single nowait
{
neighVec[i].index = i;
mesh.getBoxIntersecTets(mesh.vertexList->at(i), &neighVec[i]);
}
}
verSize大约是90k,而getBoxIntersecTets相当昂贵。所以我希望代码能够充分利用四核CPU。 但CPU使用率仅为25%左右。 有什么想法吗?
我也尝试使用 omp parallel 进行构造,但同样的故事。
getBoxIntersecTets 使用 STL unordered_set、vector 和 deque,但我想 OpenMP 应该对它们不可知,对吧?
谢谢。
I'm trying to use OpenMP to make some code parallel.
omp_set_num_threads( 8 );
#pragma omp parallel
for (int i = 0; i < verSize; ++i)
{
#pragma omp single nowait
{
neighVec[i].index = i;
mesh.getBoxIntersecTets(mesh.vertexList->at(i), &neighVec[i]);
}
}
verSize is about 90k, and getBoxIntersecTets is quite expensive. So I expect the code to fully utilize a quad core cpu.
However the CPU usage is only about 25%.
Any ideas?
I also tried using omp parallel for construct, but same story.
getBoxIntersecTets uses STL unordered_set, vector and deque, but I guess OpenMP should be agnostic about them, right?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,#pragma omp single 正在禁用并行执行,您肯定不希望这样。
请尝试这样做:
原始代码的问题是不同的线程正在使用数组的相邻元素。相邻元素在内存中彼此相邻放置,这意味着它们可能共享一个缓存行。由于只有一个核心可以同时拥有一个缓存行,因此只有一个核心可以同时完成工作。或者更糟糕的是,您的程序可能会花费更多时间来转移缓存行的所有权,而不是执行实际工作。
通过引入临时变量,每个worker可以在独立的缓存行上进行操作,然后只需要访问最后的共享缓存行来存储结果。如果第一个参数是通过非常量引用传递的,则应该对它执行相同的操作。
First up,
#pragma omp single
is disabling parallel execution, you definitely don't want that.Try this instead:
The problem with your original code is that different threads are using adjacent elements of an array. Adjacent elements are placed next to each other in memory, which means they probably share a cache line. Since only one core can own a cache line at once, only one core can get work done at once. Or worse, your program may spend more time transferring ownership of the cache line than doing actual work.
By introducing a temporary variable, each worker can operate on an independent cache line, and then you only need access to the shared cache line at the end to store results. You should do the same thing for the first parameter if it's being passed by non-const reference.