Testing The Code Performance Of PLINQ

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.
  1. var source = Enumerable.Range(1, 100000);  
  2. var source2 = Enumerable.Range(1, 100000);  
  3. var evenswithParallel = source.AsParallel().Where(x => x % 2 == 0).ToList();  
  4. 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.
  1. var source = Enumerable.Range(1, 100000);  
  2. var source2 = Enumerable.Range(1, 100000);  
  3. Stopwatch sw = Stopwatch.StartNew();  
  4. var evenswithParallel = source.AsParallel().Where(x => x % 2 == 0).ToList();  
  5. sw.Stop();  
  6. Console.WriteLine("With Parallel "+sw.ElapsedMilliseconds);  
  7. sw = Stopwatch.StartNew();  
  8.   
  9. var evenswithoutParallel = source2.Where(x => x % 2 == 0).ToList();  
  10. sw.Stop();  
  11. Console.WriteLine("Without Parallel "+sw.ElapsedMilliseconds);  
You should see an output, as shown below:
 
output
 
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


Similar Articles