我对我是否应该使用Parallel.For()有一些疑问。我做了一个简单的测试,它强烈反对并行化。在什么情况下以及如何正确使用Parallel.For()和PLinq?这里是我的测试代码:并行For循环与简单for循环在C#中。速度测试
class Wrapper
{
public void Sequential()
{
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < 1000; i++)
{
DauntingOp(i);
DauntingOp(i + 9000);
DauntingOp(i - 8521);
DauntingOp(i);
DauntingOp(i + 9000);
DauntingOp(i - 8521);
}
Console.WriteLine("For = ms: {0}", sw.ElapsedMilliseconds);
}
public void ParallelFor()
{
Stopwatch sw = Stopwatch.StartNew();
Parallel.For(0, 1000, (elem) =>
{
DauntingOp(elem);
DauntingOp(elem + 9000);
DauntingOp(elem - 8521);
DauntingOp(elem);
DauntingOp(elem + 9000);
DauntingOp(elem - 8521);
});
Console.WriteLine("Parallel For = ms: {0}", sw.ElapsedMilliseconds);
}
private void DauntingOp(int index)
{
try
{
long val = index;
for (int i = 0; i < 1000; i++)
{
long a = val + 345678;
long b = a + 4567;
long c = a - b;
long d = long.Parse(new Random().Next().ToString());
long x = d - a - b - c;
long y = long.Parse(new Random().Next().ToString()) - (long.Parse(new Random().NextDouble().ToString()) + 345 - x);
}
}
catch { }
finally
{
try
{
long a = 345678;
long b = a + 4567;
long c = a - b;
long d = long.Parse(new Random().Next().ToString());
long x = d - a - b - c;
long y = long.Parse(new Random().Next().ToString()) - (long.Parse(new Random().Next().ToString()) + 345 - x);
}
catch { }
}
}
}
class Program
{
static void Main(string[] args)
{
Wrapper wrapper = new Wrapper();
wrapper.Sequential();
wrapper.ParallelFor();
Console.Read();
}
}
结果:
For = ms: 22645
Parallel For = ms: 29020
不应该的Parallel.For更快?
我要说的是,管理并行循环的成本outweighing工作的成本在这种情况下,正在做。如果你正在做的事情需要更长时间,例如连接到数据库并在事务中插入一些记录,那么你可能会发现并行循环更快。顺便说一句,对于将i + 9000传递给DauntingOp的情况,该方法不会在try中执行任何操作,因为index已经是1000+,因此这些调用不会为您的测试添加任何有意义的内容。 – DeanOC
我在你的机器上运行你的代码,差异很小。我刚刚启用了多个内核;我会重新启动并重试,然后再回到你身边。 –
这取决于您的CPU有多少个内核。如果它的单核心然后并行的将由于线程上下文切换的开销而工作得更慢。 – serhiyb