【发布时间】:2012-09-26 17:30:23
【问题描述】:
在我的应用程序中,我有一个运行大约一千万个项目的 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 时的典型加速因素吗?或者有没有办法从中获得更多收益(无需切换到 GPU 实现)?
【问题讨论】:
-
Node::update()是做什么工作的? IO?直CPU? -
我认为您需要通过探查器运行它。如果你的 for 循环只占你实际时间的 30%,那么减少 20% 是惊人的。但是谁知道atm。
-
update函数中不涉及 IO。上面写着:void Node::update() { p[1] = - 6 * p[0] + n1->p[0] + n2->p[0] + n3->p[0] + n4->p[0] + n5->p[0] + n6->p[0]; }