Parallel Linq to Object collection

走远了吗. 提交于 2019-12-11 07:14:38

问题


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; }
}

Result of above code is

Time Elapsed: 6:411 Seconds:MilliSeconds in Paralel mode


Time Elapsed: 6:68 Seconds:MilliSeconds in Normal mode


回答1:


  • 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.

  • Use the System.Diagnostics.Stopwatch class for your measurements; it has much better precision.



来源:https://stackoverflow.com/questions/8745203/parallel-linq-to-object-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!