问题描述
下面是code
using(var context=new AventureWorksDataContext())
{
IEnumerable<Customer> _customerQuery = from c in context.Customers
where c.FirstName.StartsWith("A")
select c;
var watch = new Stopwatch();
watch.Start();
var result = Parallel.ForEach(_customerQuery, c=>Console.WriteLine(c.FirstName));
watch.Stop();
Debug.WriteLine(watch.ElapsedMilliseconds);
watch = new Stopwatch();
watch.Start();
foreach (var customer in _customerQuery)
{
Console.WriteLine(customer.FirstName);
}
watch.Stop();
Debug.WriteLine(watch.ElapsedMilliseconds);
}
}
问题是,Parallel.ForEach需要大约400 ms和经常需要Foreach源40MS左右。那么究竟我是做错了什么/你为什么不这项工作作为我希望它。
The problem is, Parallel.ForEach takes about 400 MS vs a regular Foreach takes about 40MS. So What exactly am i doing wrong/ Why doesn't this work as I expect it.
推荐答案
假设你有执行任务。比方说,你是一名数学老师,你有二十论文档次。这需要你两分钟级的文件,所以它会带你40分钟左右。
Suppose you have a task to perform. Let's say you're a math teacher and you have twenty papers to grade. It takes you two minutes to grade a paper, so it's going to take you about forty minutes.
现在让我们假设你决定要聘请一些助手来帮助你等级的论文。这需要你一个小时找到4助理。你每次取四个文件和你八分钟全部搞定。你交易40分钟工作68分钟,共包括额外的时间来寻找助理的工作,所以这不是一个储蓄。寻找助理的开销比自己做的工作的成本更大。
Now let's suppose that you decide to hire some assistants to help you grade papers. It takes you an hour to locate four assistants. You each take four papers and you are all done in eight minutes. You've traded 40 minutes of work for 68 total minutes of work including the extra hour to find the assistants, so this isn't a savings. The overhead of finding the assistants is larger than the cost of doing the work yourself.
现在假设你有两万篇等级,所以它会带你约4分钟。现在,如果你花一个小时找助理,这是一个双赢。你每次取4000篇,共计8060几分钟而不是40000分钟未完成的,几乎5.因子的储蓄寻找助理的开销基本上是无关紧要的。
Now suppose you have twenty thousand papers to grade, so it is going to take you about 40000 minutes. Now if you spend an hour finding assistants, that's a win. You each take 4000 papers and are done in a total of 8060 minutes instead of 40000 minutes, a savings of almost a factor of 5. The overhead of finding the assistants is basically irrelevant.
并行化的不是免费的的。 分拆工作之间不同的线程的成本需要相比,工作的每个线程完成的工作量是很小的。
这篇关于Parallel.ForEach比慢的ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!