concept Parallel in category .net

appears as: Parallel, Parallel
Concurrency in .NET

This is an excerpt from Manning's book Concurrency in .NET.

Table 1.1  Benchmark of sorting with Quicksort
Serial Parallel Parallel 4 threads Parallel 8 threads
6.52 12.41 4.76 3.50

A prime candidate for parallelism is a large data set where a CPU-intensive operation can be performed independently on each element. In general, loops in any form (for loop, while loop, and for-each loop) are great candidates to exploit parallelism. Using Microsoft’s TPL, reshaping a sequential loop into a parallel one is an easy task. This library provides a layer of abstraction that simplifies the implementation over common parallelizable patterns that are involved in data parallelism. These patterns can be materialized using the parallel constructs Parallel.For and Parallel.ForEach offered by the TPL Parallel class.

Figure 4.5 Using a Parallel.For construct, this benchmark compares the execution time of the sequential loop, which runs in 9.038 seconds, against the parallel, which runs in 3.443 seconds. The Parallel.For loop is about three times faster than the sequential code. Moreover, the last column on the right is the execution time of the over-saturated parallel loop, where both outer and inner loops are using the Parallel.For construct. The over-saturated parallel loop runs in 5.788 seconds, which is 50% slower than the non-saturated version.

c04-05.png
Listing 4.4 Parallel sum of prime numbers using a Parallel.For loop construct
int len = 10000000;
long total = 0;   #1  

Func<int, bool> isPrime = n => {   #2  
     if (n == 1) return false;
     if (n == 2) return true;
     var boundary = (int)Math.Floor(Math.Sqrt(n));
     for (int i = 2; i <= boundary; ++i)
              if (n % i == 0) return false;
     return true;
};

Parallel.For(0, len, i => {   #3  
 if (isPrime(i))   #4  
 total += i;   #4  
});

#1   The total variable is used as the accumulator.
#2   The function isPrime determines if a number is a prime.
#3   The Parallel.For loop construct uses an anonymous lambda to access the current counter.
#4   If the counter i is a prime number, it’s added to the accumulator total.