TPL - Parallel with Partitioner Class

Scenario:

Process data in parallel

Solution:

MSDN: Slower performance is caused by the overhead involved in partitioning the data and the cost of invoking a delegate on each loop iteration. Partitioner.Create enables sequential loop for the delegate body, so that the delegate is invoked only once per partition, instead of once per iteration.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
     public class PartitionerClassParallel
        {
            static void Main(string[] args)
            {
                var data = Enumerable.Range(0, 100).ToArray();
                var partitioner = Partitioner.Create(0, data.Length);
                var results = new double[data.Length];
    
                //range is to - from per partition and delegate called once per partition.
                Parallel.ForEach(partitioner, (range, loopState) =>
                {
                    for (int i = range.Item1; i < range.Item2; i++)
                    {
                        results[i] = data[i] * 2;
                    }
                });
    
                foreach (var d in results)
                {
                    Console.Write("{0} ", d);
                }
            }
        }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...