4 minute read

Which machine do you have? Intel Core 2 Duo, Quad Processor, AMD Turion?

All these machines and many more in the market are multi-core machines, but not all your software programs are! So eventually you do not get the best out of your software even if you have spent more money behind buying a multi-core processor!

So why don't we design our software programs to use multi-core architecture and speed up the processing and deliver faster & better results?  Yes, it becomes little complex if you were to write code considering different threads, their joining at right time and thread-safety (something you and I did until now)! But .NET 4.0 looks more promising considering the Parallel Programming using Task Parallel Library (TPL) or now called as Parallel API

With Parallel API, you can direct .NET 4.0 compiler to execute the core processing in parallel i.e. execute it on a different core-processor.  This means, on a Dual Processor with Parallel API you can expect twice better performance and with a Quad Processor with Parallel API the performance could be four times better!

Sounds good, isn't it?

So, let's have a very small example of using Parallel API. Say we want to generate a single-dimensional array with the some non-dependent logic. The term 'non-dependent' refers to a scenario where there is no data dependency between values at 2 indices of the array. In simpler words, array[x] is not dependent on value of array[y] so that computation of array[x] and array[y] can happen in parallel.

Traditional Code:

[sourcecode language='c#']
int size = 1000;
for (int i = 0; i < size; i++)
{
Thread.Sleep(10);
}
[/sourcecode]

With Parallel API:

[sourcecode language='c#']
Parallel.For(0, size, delegate(int i)
{
Thread.Sleep(10);
});
[/sourcecode]

Check the performance!

Performance Environment:

  • Intel Core 2 Duo 2.1 GHz
  • 2 GB RAM
  • Windows 7

With 1000 iterations each having a sleep duration of 10 Milli-Seconds, the execution time was

Traditional Code: 10.007 seconds
Parallel API Code: 2.93 seconds

This clearly depicts that Parallel API fastens the execution time. But wait!

In the examples taken above, there was no particular sequence that got executed.  In case we want a particular sequence to be executed in the core processing then Parallel API does not help us much.  We need to get to our basics of Threads and Delegates to ensure appropriate sequencing.

Looking at features & faster executing speed as offerings from Parallel API, I am sure .NET 4.0 will get accepted as a standard language for new / re-engineering applications. Many more migration projects to come! :-)