C# Parallel.For

With the advent of C# 4.0 you can now write code to more efficiently use multiple core machines. I will show a trivial example on how to do this. This code reads through a directory and lists all the files. Now while the example itself isn't that complicated I will show some timings and benefits on my Intel duo core 2 machine. Running on even more cores would show an even bigger result. This kind of computing really shines when you're dealing with large amounts of data or very intensive computations. This test sums up 10 million random integers.



using System.Threading.Tasks;

static void Main( string[] args )
{
      int[] values = new int[10000000];

      Random r = new Random( DateTime.Now.Millisecond );

      double sum = 0;

      for( int i = 0; i < values.Length; i++ )
      {
          values[i] = r.Next( 0, 10 );
      }

      DateTime start = DateTime.Now;
      DateTime end;

      // run the test in parallel
      Parallel.For( 0, values.Length, delegate( int i )
      {
          sum += values[i];
      } );

      end = DateTime.Now;

      TimeSpan t = end - start;

      Console.WriteLine( "Parrallel For time is: " + t.TotalMilliseconds + ", sum is: " + sum );

      start = DateTime.Now;

      // run the test in sequential
      for( int i = 0; i < values.Length; i++ )
      {
          values[i] = r.Next( 0, 10 );
      }

      end = DateTime.Now;

      t = end - start;

      Console.WriteLine();
      Console.WriteLine( "Regular For time is: " + t.TotalMilliseconds + ", sum is: " + sum );

      Console.ReadKey();
}

The Parallel.For looks almost exactly like the regular for. The main difference is you have to add in the delegate(int) at the end. This is used when the compiler creates the different threads to use on the various CPUs. A more detailed explanation can be found here:

MSDN Link

Now onto the results!

After many runs the parallel code ran anywhere from almost twice as fast to 100 ms faster. Now this is just a random summation of integers. Even more computationally complex tasks should see even more benefit

Some results:

Comments

Popular posts from this blog

String.Replace vs Regex.Replace

C# Producer Consumer using Rabbit MQ

C# Form Application in Kiosk Mode/Fullscreen