Click here to Skip to main content
15,880,967 members
Articles / Programming Languages / C# 4.0

Faster faster loops

Rate me:
Please Sign up or sign in to vote.
4.85/5 (8 votes)
3 May 2010CPOL1 min read 14K   18   1
Using the Task Parallel Library in .NET 4.0

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:

C#
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:

C#
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.


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO
United Kingdom United Kingdom
A developer for over 30 years, I've been lucky enough to write articles and applications for Code Project as well as the Intel Ultimate Coder - Going Perceptual challenge. I live in the North East of England with 2 wonderful daughters and a wonderful wife.

I am not the Stig, but I do wish I had Lotus Tuned Suspension.

Comments and Discussions

 
GeneralParallel memory access PinPopular
Danny Ruijters10-May-10 21:13
Danny Ruijters10-May-10 21:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.