0

I wrote a little program to check the performance of Sum() working on an AsParallel() enumeration (i.e. PLINQ).

First, I generate an IEnumerable. The range is not particularly large because then the LINQ Sum() would result in an overflow.

IEnumerable<int> range = Enumerable.Range(1, 30000);

My first benchmark is performed using a regular loop:

var stopwatch = new Stopwatch();
stopwatch.Start();
int total = 0;
foreach(int x in range)
{
    total += x;
}
stopwatch.Stop();

Console.WriteLine("Sum 1: {0}; time: {1}", total, stopwatch.Elapsed);

My second benchmark uses LINQ Sum():

stopwatch.Restart();
int total2 = range.Sum();
stopwatch.Stop();

Console.WriteLine("Sum 2: {0}; time: {1}", total2, stopwatch.Elapsed);

My third benchmark uses PLINQ Sum():

stopwatch.Restart();
int total3 = range.AsParallel().Sum();
stopwatch.Stop();

Console.WriteLine("Sum 3: {0}; time: {1}", total3, stopwatch.Elapsed);

Here are some results:

Sum 1: 450015000; time: 00:00:00.0004210
Sum 2: 450015000; time: 00:00:00.0003545
Sum 3: 450015000; time: 00:00:00.0427375

Why is the PLINQ version (Sum 3) so much slower than the others? Also, why is the LINQ Sum() (Sum 2) faster than the plain loop (Sum 1)?

Community
  • 1
  • 1
Gigi
  • 28,163
  • 29
  • 106
  • 188
  • 1) Your samples are too small. 2) The amount of work is too small for Parallel. – H H Jun 15 '14 at 08:35
  • The __Related__ column contains almost a dozen duplicates, I just picked the top one. – H H Jun 15 '14 at 08:37
  • This is not the same. A sum is always going to be a small amount of work for each unit. So what's the use of PLINQ sum in that case? – Gigi Jun 15 '14 at 08:39
  • The use of Sum() is to calculate the sum. Make sure to go throug the column on the right of this page. – H H Jun 15 '14 at 08:53
  • I know what Sum() does, and I know there's a column on the right of this page, as you so fondly remind me every time. I'm asking what's the point if it's always going to be a small amount of work, and therefore PLINQ will always be slower. Also if you read my question, there is more than one question at the end. It's a amazing with what zeal questions are marked as duplicate on this site. – Gigi Jun 15 '14 at 09:35

0 Answers0