在我的应用程序中,我有一个运行超过一千万个项目的 for 循环,如下所示:
int main(int argc, char* argv [])
{
unsigned int nNodes = 10000000;
Node** nodeList = new Node* [nNodes];
initialiseNodes(nodeList); // nodes are initialised here
for (unsigned int ii = 0l ii < nNodes; ++ii)
nodeList[ii]->update();
showOutput(nodeList) // show the output in some way
}
我不会详细说明节点是如何准确初始化或显示的。重要的是 Node::update()
方法是一个小方法,独立于其他节点。因此,并行执行此 for 循环将非常有利。由于是小事,这次想远离OpenCL/CUDA/OpenMP,所以改用了C++的Concurrency::parallel_for
。那么代码看起来像这样:
#include <ppl.h>
int main(int argc, char* argv [])
{
unsigned int nNodes = 10000000;
Node** nodeList = new Node* [nNodes];
initialiseNodes(nodeList); // nodes are initialised here
Concurrency::parallel_for(unsigned int(0), nNodes, [&](unsigned int ii) {
nodeList[ii]->update();
});
showOutput(nodeList) // show the output in some way
}
我发现这确实会稍微加快程序的速度,但通常只提高 20% 左右。坦率地说,我期待更多。有人可以告诉我这是否是使用 parallel_for
时的典型加速因素?或者有没有办法从中获得更多 yield (无需切换到 GPU 实现)?
最佳答案
在一个问题上投入更多核心并不总是会带来改善。事实上,在最坏的情况下,它甚至会降低性能。从使用多核中获益取决于很多因素,例如所涉及的共享数据量。有些问题本质上是可并行化的,有些则不是。
关于c++ - 使用 Concurrency::parallel_for() 的边际性能增益,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12607216/