Most of us have heard about how to do parallel programming, using Parallel class (
PLINQ), provided in the .NET framework.
In this article, I would like to discuss two things about how parallelism cannot be applied in certain cases.
Below is the simple code, which gets the range of an integer from 1 to 100000 and then uses TPL. It is trying to get the list out of the source, where the numbers are even.
- var source = Enumerable.Range(1, 100000);
- var source2 = Enumerable.Range(1, 100000);
- var evenswithParallel = source.AsParallel().Where(x => x % 2 == 0).ToList();
- var evenswithoutParallel = source2.Where(x => x % 2 == 0).ToList();
Usually after running these code lines, it is hard to say, which line got executed in how many milliseconds (of course).
Here is how you can test the performance of the code, mentioned above. You can wrap the code with the Stopwatch class object, which actually counts the ticks, while the code is being executed.
- var source = Enumerable.Range(1, 100000);
- var source2 = Enumerable.Range(1, 100000);
- Stopwatch sw = Stopwatch.StartNew();
- var evenswithParallel = source.AsParallel().Where(x => x % 2 == 0).ToList();
- sw.Stop();
- Console.WriteLine("With Parallel "+sw.ElapsedMilliseconds);
- sw = Stopwatch.StartNew();
-
- var evenswithoutParallel = source2.Where(x => x % 2 == 0).ToList();
- sw.Stop();
- Console.WriteLine("Without Parallel "+sw.ElapsedMilliseconds);
You should see an output, as shown below:
Interesting, isn’t it?
Well, here is the fact. Parallel increases the processing speed but not in every case. Using Parallel (PLINQ) has its own complexity and certain overhead, where it divides the source of the data into the possible groups (up to 64) in order to utilize all the cores of the processor available. This sometimes isn’t effective on the small data sets. Also, while selecting the data out of the source, and that too with some calculation, requires extra resources and time, which leads to the output shown above. Using PLINQ, it took 60 milliseconds whereas, without parallel, it finished in just 4 milliseconds.
For a more detailed understanding of speeding in PLINQ, please refer to this
link.