BANGALORE, INDIA: In the article 'Programming for Multi-core Processors' carried in this issue, we have talked about how you can utilize your the capabilities of your multi-core machine. Here, we'll talk about another way of doing the same by using Task Parallel Library (TPL).
TPL is designed to automatically utilize all the processors in a machine which results in enhanced performance, as displayed in this sample implementation. TPL contains algorithms that automatically adapt to a particular machine. For example, if you are running a parallel for loop on a single core machine, it will perform as normal for loop.
But if the same is run on a multi-core machine, it will parallelize automatically. If any exception is thrown in any of the iterations, all iterations are canceled and the first thrown exception is re-thrown in the calling thread ensuring that exceptions are properly propagated and never lost. One point to keep in mind while using TPL is that, it does not support synchronization therefore, it is important for programmers to take in account safe synchronous execution.
Implementation To show how parallel processing can boost your application performance, we have created a sample code that measures time of processing. We ran this code in three different scenarios. First, we used simple 'for' loop and calculated time of execution on single core, then we used 'Parallel.For' loop to parallelize execution of conventional 'for' loop.
We executed 'Parallel.For' loop on two different machines one with two cores and other with four. To start with, create a console application in Visual Studio. We have used C# as programming language. Now add 'System.Threading' reference to program and add following code:
The comparative graph shows execution of 'for' loop and 'Parallel.For' loop. Parallel for loop is executed on quad core and dual core machines.
using System.Linq; using System.Text;
namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var source = Enumerable.Range(1, 1000); using System.Linq; using System.Text; using System.Threading;
namespace ParallelTPL { class Program { static void Main(string[] args) {
DateTime startTime = DateTime.Now; Console.WriteLine(startTime);
/*for (int i = 0; i < 1000; i++) { Thread.Sleep(100); Console.WriteLine(i); }*/
Parallel.For(0, 1000, delegate(int i) { Thread.Sleep(100); Console.WriteLine(i); });
DateTime stopTime = DateTime.Now; Console.WriteLine(stopTime);
TimeSpan duration = stopTime - startTime; Console.WriteLine(duration);
Console.ReadLine(); } } }
Get most out of your technology infrastructure investments with Dell
About CIOL | Media Kit | Site Map | Contact Us | Help | Write to us | Jobs@CyberMedia | Privacy Policy
Copyright © CyberMedia India Online Ltd. All rights reserved. Usage of content from web site is subject to Terms and Conditions.