Parallel Computing: PLINQ

Visual Studio 2010 has new API for LINQ (Language Integrated Query). This helps us to implement the power of Parallel Computing in declarative manner.

LINQ without Parallel Extension

It will take 3 sec for 28 thousand elements.

static void Main(string[] args)

{

    Stopwatch sw = Stopwatch.StartNew();

   

    DoIt();

    Console.WriteLine("Elapsed = " + sw.ElapsedMilliseconds.ToString());

    Console.ReadLine();

}

private static void DoIt()

{

    IEnumerable<int> arrInt = Enumerable.Range(1, 4000000);

    var q =

        from n in arrInt

        where IsPrime(n)

        select n.ToString();

    List<string> list = q.ToList();

    Console.WriteLine("Elements : " + list.Count.ToString());

}

private static bool IsPrime(int p)

{

    //Find the prime number

    int upperBound = (int)Math.Sqrt(p);

    for (int i = 2; i < upperBound; i++)

    {

        if (p % i == 0) return false;

    }

    return true;

}

LINQ with Parallel Extension

With a very simple change in query this will take around 1.5 sec for the same number of elements.

var q =

    from n in arrInt.AsParallel()

    where IsPrime(n)

    select n.ToString();

Greenroom

What’s the magic? When we use .AsParallel() it does cast the list of integers into ParallelEnumerable class and calls a different Where method which implements the new “Task” API.

With Lambda expression this would look more clear.

Before

var q = arrant

    .Where(n => IsPrime(n))

    .Select(n => n.ToString());

Class: Enumerable

Method:     

        public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

After (while using AsParallel())

Code:

var q = arrInt.AsParallel()

    .Where(n => IsPrime(n))

    .Select(n => n.ToString());

Class : ParallelEnumerable

Method :

        public static ParallelQuery<TSource> Where<TSource>(this ParallelQuery<TSource> source, Func<TSource, bool> predicate);

The above time will vary based on CPU power and availability.

Namoskar!!!

Comments

  • Anonymous
    November 19, 2009
    This is awesome! Thanks for posting. Just one error in your IsPrime calculation The  "for (int i = 2; i < upperBound; i++)" needs to change to " for (int i = 2; i <= upperBound; i++)"