.net并行库的一些记录
private static void Wrong()
{
Stopwatch watch = new Stopwatch();
watch.Start();
Parallel.For(0, 500000, p =>
{
int c = p;
});
watch.Stop();
long tempParalleTime = watch.ElapsedMilliseconds;
watch.Restart();
for (int i = 0; i < 500000; i++)
{
int c = i;
}
watch.Stop();
Console.WriteLine("顺序执行用时:" + watch.ElapsedMilliseconds);
Console.WriteLine("并行库用时:" + tempParalleTime);
}
Stopwatch watch = new Stopwatch();
watch.Start();
Parallel.For(0, 500000, p =>
{
int c = p;
});
watch.Stop();
long tempParalleTime = watch.ElapsedMilliseconds;
watch.Restart();
for (int i = 0; i < 500000; i++)
{
int c = i;
}
watch.Stop();
Console.WriteLine("顺序执行用时:" + watch.ElapsedMilliseconds);
Console.WriteLine("并行库用时:" + tempParalleTime);
}
这段并行代码看似没问题,可是执行出来的结果如下
明明并行了,为什么还是慢呢,简直有些不可思议,其实MSDN上有完整的解释:
System.Threading.Tasks.Parallel.For loop has a small body, it might perform more slowly than the equivalent sequential loop.’ data-guid=”a5a0118a06f0a1b142f8185f50ced09e”>当 System.Threading.Tasks.Parallel.For 循环的循环体很小时,它的执行速度可能比等效的顺序循环更慢。 对数据进行分区所涉及的开销以及调用每个循环迭代上的委托的开销导致了性能降低。
恩,其实原因就是所谓的循环体太小,这里的循环体太小,其实这里不是指代码的长度,而是指循环体里面做的事情是否比较费时。其实改写成下面这样
private static void Right()
{
Stopwatch watch = new Stopwatch();
watch.Start();
Parallel.For(0, 50, p =>
{
WebClient wb = new WebClient();
string content = wb.DownloadString(@"http://www.baidu.com");
});
watch.Stop();
long tempParallelTime = watch.ElapsedMilliseconds;
watch.Restart();
for (int i = 0; i < 50; i++)
{
WebClient wb = new WebClient();
string content = wb.DownloadString(@"http://www.baidu.com");
}
watch.Stop();
Console.WriteLine("顺序执行用时:" + watch.ElapsedMilliseconds);
Console.WriteLine("并行库用时:" + tempParallelTime);
}
Stopwatch watch = new Stopwatch();
watch.Start();
Parallel.For(0, 50, p =>
{
WebClient wb = new WebClient();
string content = wb.DownloadString(@"http://www.baidu.com");
});
watch.Stop();
long tempParallelTime = watch.ElapsedMilliseconds;
watch.Restart();
for (int i = 0; i < 50; i++)
{
WebClient wb = new WebClient();
string content = wb.DownloadString(@"http://www.baidu.com");
}
watch.Stop();
Console.WriteLine("顺序执行用时:" + watch.ElapsedMilliseconds);
Console.WriteLine("并行库用时:" + tempParallelTime);
}
就会发现
并行库用时明显少了,当然,这里其实更应该用thread.sleep模拟下就好,毕竟访问外部IO是不太稳定的,不过这已经足够说明问题了。写这类并行代码需要注意的地方很多,一个不留神,很有可能比顺序执行更慢。