MaxDegreeOfParallelism = Environment.ProcessorCount slows down execution time on my CPU

Viewed 16671

I have the following program (that I got from http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx) that splits a task up using Parallel.For loop

class Program
{
    static void Main(string[] args)
    {
        var watch = Stopwatch.StartNew();


        Parallel.For(2, 20, (i) =>
        {
            var result = SumRootN(i);
            Console.WriteLine("root {0} : {1} ", i, result);
        });

        Console.WriteLine(watch.ElapsedMilliseconds);
        Console.ReadLine();
    }

    public static double SumRootN(int root)
    {
        double result = 0;
        for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result;
    }
}

When I run this test several times I get times of:

1992, 2140, 1783, 1863 ms etc etc.

My first question is, why are the times always different?? I am doing the exact same calculations each time yet the times vary each time.

Now when I add in the following code to make use of all the available processors on my CPU:

        var parallelOptions = new ParallelOptions
        {
            MaxDegreeOfParallelism = Environment.ProcessorCount    (On my CPU this is 8)
        };

        Parallel.For(2, 20, parallelOptions, (i) =>
        {
            var result = SumRootN(i);
            Console.WriteLine("root {0} : {1} ", i, result);
        });

I notice that the execution times actually increase!! The times are now:

2192, 3192, 2603, 2245 ms etc etc.

Why does this cause the times to increase? Am I using this wrong?

1 Answers
Related