C# .Net LINQ, PLINQ and Parallel.For

Another look into the parallel execution and understanding how to achieve the most effective results, I’ll do some more experiments with this to see what works best.

using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace CsharpParallelForDemo
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Processing for loop with PLINQ..");
            Console.WriteLine();
            for (var i = 1; i <= Environment.ProcessorCount; i++)
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                       .WithDegreeOfParallelism(i)
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                result = null;
            }

            Console.WriteLine();
            Console.WriteLine("Processing Parallel for loop with LINQ..");
            Console.WriteLine();

            Parallel.For(1, 5, (i) =>
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                result = null;
            });

            Console.WriteLine();
            Console.WriteLine("Processing Parallel for loop with PLINQ..");
            Console.WriteLine();

            Parallel.For(1, 5, (i) =>
            {
                var myRange = Enumerable.Range(1, 1000000);

                var stopWatch = Stopwatch.StartNew();

                var result = myRange.AsParallel()
                       .WithDegreeOfParallelism(i)
                       .Select(x => x);

                result.ToList();

                stopWatch.Stop();

                Console.WriteLine("Number of cores: {0} Time: {1:FFFFFFF}", i, stopWatch.Elapsed);

                result = null;
            });


            Console.ReadKey();
        }
    }
}

Returns:

Processing for loop with PLINQ..

Number of cores: 1 Time: 1022974
Number of cores: 2 Time: 0653203
Number of cores: 3 Time: 0719758
Number of cores: 4 Time: 0524761

Processing Parallel for loop with LINQ..

Number of cores: 2 Time: 0582022
Number of cores: 4 Time: 0644796
Number of cores: 3 Time: 0912731
Number of cores: 1 Time: 1034905

Processing Parallel for loop with PLINQ..

Number of cores: 3 Time: 0717623
Number of cores: 2 Time: 0978785
Number of cores: 4 Time: 0979141
Number of cores: 1 Time: 1378484

Leave a Reply

Your email address will not be published. Required fields are marked *