并行Linq到对象集合 [英] Parallel Linq to Object collection
问题描述
当我尝试使用Plinq(Parallel linq)进行对象收集时遇到了一个基本问题,并且我发现Plinq Vs的正常操作在执行时间方面没有太大差异.任何人都可以检查我的代码并建议我为什么会这样.我已经在i7处理器中运行了此代码.
I got a basic question when I tried with Plinq (Parallel linq ) to object collection and I observed that Plinq Vs normal operation does not have much difference in terms of execution time. Could anybody can check my code and advice me why so happening. I have run this code in i7 processor.
class Program
{
static void Main(string[] args)
{
new Program().Plinq();
new Program().linq();
Console.ReadLine();
}
void Plinq()
{
DateTime startTime = DateTime.Now;
var query1 = (from port in new XpressEntities().Portfolios.Take(1000000)
select new port { PortId = port.PORT_ID, CFAC = port.CFAC }).ToList<port>();
query1.AsParallel().Where(e => e.PortId == 0);
TimeSpan ts = DateTime.Now.Subtract(startTime);
Console.WriteLine("Time Elapsed: {0} Seconds:MilliSeconds in Paralel mode", ts.Seconds + ":" + ts.Milliseconds);
}
void linq()
{
DateTime startTime = DateTime.Now;
var query1 = (from port in new XpressEntities().Portfolios.Take(1000000)
select new port { PortId = port.PORT_ID, CFAC = port.CFAC }).ToList<port>();
query1.Where(e => e.PortId == 0);
TimeSpan ts = DateTime.Now.Subtract(startTime);
Console.WriteLine("Time Elapsed: {0} Seconds:MilliSeconds in Normal mode", ts.Seconds + ":" + ts.Milliseconds);
}
}
class port
{
public int PortId { get; set; }
public string CFAC { get; set; }
}
以上代码的结果为
经过的时间:6:411秒:并行模式下的秒数
Time Elapsed: 6:411 Seconds:MilliSeconds in Paralel mode
经过的时间:6:68秒:正常模式下秒数为秒
Time Elapsed: 6:68 Seconds:MilliSeconds in Normal mode
推荐答案
-
Where()返回IEnumerable,并且不会导致查询被评估.您需要明确评估答案(例如,使用ToList()).
Where() returns an IEnumerable and does not result in the query being evaluated. You need to explicity evaluate the answer (for example, using ToList()).
在启动线程时需要考虑一些开销,因此您的工作负载必须花费足够的时间来执行,这样您才能观察到差异.除非条件评估起来很昂贵,否则在可能适合内存的列表上进行筛选可能还不够.
There is some overhead in starting up threads which must be taken account of, so your work load must take sufficient time to execute that you can observe a difference. Filtering may not be enough on a list which will fit in memory unless the criteria are expensive to evaluate.
使用System.Diagnostics.Stopwatch类进行测量;精度更高.
Use the System.Diagnostics.Stopwatch class for your measurements; it has much better precision.
这篇关于并行Linq到对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!