Tuesday, March 17, 2009

.NET Parallel Computation Made Easy : System.Threading.Parallel

I had conduct a simple experiment for some time ago. It's about the performance of .NET program running on a multi-core processor versus the same program running on the single-core one. The result from my experiment shows that if you have a normal .NET program implemented without multi-threading, there will be no significant performance difference between running it on multi-core and single-core system.

I found it hard to create a multi-thread version of my classic old "Prime Generator" program. The hardest part is I don't know the appropiate number of thread to create since I had no information about the system the program is runnning on. And the threading code just looks ugly .. developers with no multi-threading background will find it hard to understand and maintain. Take my old code for example.

The Rescue
This is where Microsoft Parallel Extensions to .NET Framework 3.5 comes in handy. It simplify the process of constructing the multithread code yourself. There are many useful stuffs under System.Threading.Parallel. But I find System.Threading.Parallel.For is the easiest to understand and utilize :)

Here is the plotting between the data set size and time used in millisecond on my machine with Intel(R) Core(TM)2 Duo CPU E6750 @ 2.66GHz. The System.Thread.Parallel.For actually takes extra computation time on the first call which makes me wonder why an ordinary for-loop outperforms parallel version at very first version of my benchmark. However, after the first call, the parallel version outperforms ordinary for-loop as expected.

I believe the results will be different on a quad core machine too :)

Hope this helps.