我在c#中有一个计算流体力学(计算流体力学),它需要花费太多的时间来计算结果。为了改进我的代码,我开始学习TPL并使用并行代码。对于顺序不重要的循环,我可以使用TPL,对于有顺序的循环,PLINQ是唯一的方法。我说的对吗?
作为第一步,我将循环改为Parallel.For,有趣的是发现运行时增加了!
我的代码示例:
for (int i = 0; i < nx; i++)
{
for (int j = 0; j < ny; j++)
{
if (!Cells[i, j, 0].IsVirtual)
{
// calculate x velocity
// calculate y velocity
}
}
}具有并行任务:
Parallel.for (0,nx, i =>
{
for (int j = 0; j < ny; j++)
{
if (!Cells[i, j, 0].IsVirtual)
{
// calculate x velocity
// calculate y velocity
}
}
});,我如何加快我的代码?,我的每个输出需要10分钟,这是非常长的时间,我至少有5000个输出。
发布于 2014-07-04 02:57:56
对于小循环,管理线程的开销可能会影响整个执行时间。如果每次迭代执行时间较长,您可能会看到不同的结果。
发布于 2014-07-04 04:08:14
在大型数据集(例如,至少50万个单元)上,您可能会遇到缓存失效的问题,因为您对内存的迭代效率很低。
如果将其更改为TPL(无论是否使用TPL),您可能会看到性能的提高(请注意我是如何将迭代从i,j切换到j,i的):
for (int j = 0; j < ny; j++)
{
for (int i = 0; i < nx; i++)
{
if (!Cells[i, j, 0].IsVirtual)
{
// calculate x velocity
// calculate y velocity
}
}
}请参见这里的解释:Why does the order of the loops affect performance when iterating over a 2D array?
https://stackoverflow.com/questions/24566053
复制相似问题