Home > .NET 4, Task Parallel Library > Faster faster loops

Faster faster loops

With multicore machines becoming more and more commonplace, it’s madness that loops can’t take use of this extra grunt. Fortunately for us, those nice guys and girls at Microsoft share our frustration with this state of affairs and have taken steps to give us loop capabilities that can take advantage of this extra capacity.

Prompted by a question on Code Project, I’d like to show a quick code sample that demonstrates a new feature in .NET 4.0 called the Task Parallel Library. With this library, it is much easier to write code in a managed language that makes use of multiple cores where available. This gives us the option to write code as parallel tasks that are run concurrently across available processors; generally resulting in significantly speeded up code.

Here’s a sample of the code that we are going to parallelize:

using System;

namespace ParallelForSample
{
  public class SingleCore
  {
    public static void Calculate(int calcVal)
    {
      // Utility contains references to stopwatch which
      // we use to display details about the time taken
      // to run this code.
      Utility util = new Utility();
      util.Start();

      int[,] G = new int[calcVal, calcVal];
      for (int k = 0; k < calcVal; k++)
        for (int i = 0; i < calcVal; i++)
          for (int j = 0; j < calcVal; j++)
            G[i, j] = Math.Min(G[i, j], G[i, k] + G[k, j]);
      util.Stop();

    }
  }
}

As you can see, this is a fairly straightforward class – it’s got three loops which are used to populate an array. Now, here’s the code rewritten to use the TPL:

using System;
using System.Threading.Tasks;

namespace ParallelForSample
{
  public class MultiCore
  {
    public static void Calculate(int calcVal)
    {
      Utility util = new Utility();
      util.Start();

      int[,] G = new int[calcVal, calcVal];

      Parallel.For(0, calcVal,
        delegate(int k)
        {
          Parallel.For(0, calcVal, delegate(int i)
          {
            for (int j = 0; j < calcVal; j++)
              G[i, j] = Math.Min(G[i, j], G[i, k] + G[k, j]);
          });
        }
      );

      util.Stop();
    }
  }
}

As you can see, the syntax is slightly different. The for loop is broken down into Parallel.For. It takes a delegate which actually performs the loop behaviour. If you download the sample and run it, you can observe the difference in behaviour and timings of the loops. Now, the difference will only be observed if you have a multiple core machine; if you don’t the loop will behave as though it’s running on a single core.

Link: parallelforsample.zip

Note: As always, when downloading from here, please rename the file so that it doesn’t end in .doc.

About these ads
  1. May 16, 2010 at 8:52 pm

    The nice guys and girls at Microsoft really know how to disappoint. Every time I see code like this wonder what in the world is going on. What methods are Parallel.for using to implement the feature? and would this not be simpler if it was implemented into the syntax of the language instead of hacked in some kinda class?

    • sam
      May 22, 2010 at 11:18 pm

      They keep disappointing and keep doing the wrong thing (actually, this exact sample is a classic misunderstanding). But this is not the blog as to criticise but only confess love. Lol!

  2. May 27, 2010 at 2:00 pm

    Nice one, Pete. I wrote some of my thoughts around these parallel features in .NET 4 in a post here: http://smehrozalam.wordpress.com/2010/03/24/a-brief-overiew-of-the-new-parallel-extensions-in-net-framework-4/

  3. December 2, 2010 at 11:24 pm

    You need to take a look at F# and async workflows too, once you get the syntax things begin to look a lot clearer…

    • peteohanlon
      December 2, 2010 at 11:28 pm

      Will do mate. Course you know a lot more about that side than I do – but I will recommend that you have a wander round Axum.

  4. Dave Thomas
    December 2, 2010 at 11:41 pm

    I have looked at that before, syntax and concepts reminds me a lot of of F#…

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The Canny Coder

Java 8 Functional Programming with Lambda Expressions

pihole.org

Adventures in theoretical computer science, with your host, chaiguy1337

Confessions of a coder

Confessions of a WPF lover

WordPress.com

WordPress.com is the best place for your personal blog or business site.

Follow

Get every new post delivered to your Inbox.

Join 39 other followers

%d bloggers like this: