By Ajay K R on Dec 19, 2016 2:18:10 AM
The hardware industry, over the last few years, has been rapidly shifting towards multiple-processor core technology. Despite having multiple core in your machine you cannot expect your sequential program to run faster in that machine. For that purpose `Parallel programming' is required which can efficiently use all the cores and execute faster.
- Task Parallel Library(TPL)
- Parallel LINQ
Task Parallel Library:
The easiest way to use parallel library is to use the same in parallel loops. If you have a loop where every iteration is doing something expensive and loop iterations are independent, you can then just launch different iterations in parallel.
The below block shows the sequential iterations:
Which can be paralleled by using TPL by following code.
Parallel LINQ(PLINQ) is a query execution engine that accepts only LINQ-to-Objects or LINQ-to-XML query and automatically utilizes multiple processor or cores for execution when they are available. With PLINQ you can transform your LINQ queries to parallel version by using the AsParallel extension method as shown below.
Lets take Ray-tracer algorithm sample to render image with both Sequential and Parallel programming and will compare the execution time in both scenarios.
Img1 shows image rendering through Sequential program and the bottom right of img1 shows the time taken to execute.
Img1: Rendering Image through Sequential Program
Img2:Rendering Image through Parallel Program
The img2 shows Image rendering through parallel programming.
It is clear from the above sample images that Parallel execution is 1.5 seconds faster than the Sequential rendering.
Lets see how the processor core has been consumed in both scenarios using performance monitor tool.
In the sequential programming graph we can observe only processor core one, highlighted with red mark, has been utilizing more and rest are least utilized.
Parallel Programming Graph
In the above Parallel programming Graph we can see all the core of the processor are equally utilized.
There are many ways to create a parallel executing program in C#. With multi-core processor there’s no excuse for creating a single threaded programs and penalize your users with unneeded delays.