我对是否应该使用Parallel.For()有疑问。我做了一个简单的测试,它强烈反对并行化。在什么情况下以及如何正确使用Parallel.For()和PLinq?这是我的测试代码:
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更快?