Parallel For loop versus simple for loop in c#. Speed test

362 views Asked by At

I have some doubt as to whether I should use a Parallel.For(). I did a simple test and it came out strongly against parallelization. In what cases and how to properly use Parallel.For() and PLinq? Here is my test code:

class Wrapper
{
    public void Sequential()
    {
        Stopwatch sw = Stopwatch.StartNew();

        for (int i = 0; i < 1000; i++)
        {
            DauntingOp(i);
            DauntingOp(i + 9000);
            DauntingOp(i - 8521);
            DauntingOp(i);
            DauntingOp(i + 9000);
            DauntingOp(i - 8521);
        }

        Console.WriteLine("For = ms: {0}", sw.ElapsedMilliseconds);
    }

    public void ParallelFor()
    {
        Stopwatch sw = Stopwatch.StartNew();

        Parallel.For(0, 1000, (elem) => 
        {
            DauntingOp(elem);
            DauntingOp(elem + 9000);
            DauntingOp(elem - 8521);
            DauntingOp(elem);
            DauntingOp(elem + 9000);
            DauntingOp(elem - 8521);
        });

        Console.WriteLine("Parallel For = ms: {0}", sw.ElapsedMilliseconds);
    }

    private void DauntingOp(int index)
    {
        try
        {
            long val = index;
            for (int i = 0; i < 1000; i++)
            {
                long a = val + 345678;
                long b = a + 4567;
                long c = a - b;
                long d = long.Parse(new Random().Next().ToString());
                long x = d - a - b - c;
                long y = long.Parse(new Random().Next().ToString()) - (long.Parse(new Random().NextDouble().ToString()) + 345 - x);
            }
        }
        catch { }
        finally
        {
            try
            {
                long a = 345678;
                long b = a + 4567;
                long c = a - b;
                long d = long.Parse(new Random().Next().ToString());
                long x = d - a - b - c;
                long y = long.Parse(new Random().Next().ToString()) - (long.Parse(new Random().Next().ToString()) + 345 - x);
            }
            catch { }
        }
    }

}

class Program
{
    static void Main(string[] args)
    {
        Wrapper wrapper = new Wrapper();
        wrapper.Sequential();
        wrapper.ParallelFor();

        Console.Read();
    }
}

Results:

For = ms: 22645
Parallel For = ms: 29020

Should not be Parallel.For faster?

1

There are 1 answers

5
Rob Lyndon On BEST ANSWER

Run the solution in release mode without debugging.

My system has four cores, which I can see using Task Manager:

enter image description here

And the benchmarking is reliably four times faster:

enter image description here

Note that you won't have multiple cores enabled in Windows 10 by default. You have to run msconfig from your Start menu, and enable multiple processors in the Boot menu:

enter image description here