共用方式為


如何:加速小型迴圈主體

Parallel.For 迴圈有小型的主體時,其執行速度可能會比同等的循序迴圈更慢,例如 C# 中的 for 迴圈和 Visual Basic 中的 For 迴圈。 效能較慢的起因是分割資料時相關的負擔,以及在每次迴圈反覆運算上叫用委派的成本。 為了解決這類情況,Partitioner 類別提供 Partitioner.Create 方法,可讓您提供循序迴圈給委派主體,讓每個資料分割只叫用一次委派,而不會每個反覆項目叫用一次。 如需詳細資訊,請參閱 PLINQ 和 TPL 的自訂 Partitioner

範例

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {

        // Source must be array or IList.
        var source = Enumerable.Range(0, 100000).ToArray();

        // Partition the entire source array.
        var rangePartitioner = Partitioner.Create(0, source.Length);

        double[] results = new double[source.Length];

        // Loop over the partitions in parallel.
        Parallel.ForEach(rangePartitioner, (range, loopState) =>
        {
            // Loop over each range element without a delegate invocation.
            for (int i = range.Item1; i < range.Item2; i++)
            {
                results[i] = source[i] * Math.PI;
            }
        });

        Console.WriteLine("Operation complete. Print results? y/n");
        char input = Console.ReadKey().KeyChar;
        if (input == 'y' || input == 'Y')
        {
            foreach(double d in results)
            {
                Console.Write("{0} ", d);
            }
        }
    }
}
Imports System.Threading.Tasks
Imports System.Collections.Concurrent

Module PartitionDemo

    Sub Main()
        ' Source must be array or IList.
        Dim source = Enumerable.Range(0, 100000).ToArray()

        ' Partition the entire source array. 
        ' Let the partitioner size the ranges.
        Dim rangePartitioner = Partitioner.Create(0, source.Length)

        Dim results(source.Length - 1) As Double

        ' Loop over the partitions in parallel. The Sub is invoked
        ' once per partition.
        Parallel.ForEach(rangePartitioner, Sub(range, loopState)

                                               ' Loop over each range element without a delegate invocation.
                                               For i As Integer = range.Item1 To range.Item2 - 1
                                                   results(i) = source(i) * Math.PI
                                               Next
                                           End Sub)
        Console.WriteLine("Operation complete. Print results? y/n")
        Dim input As Char = Console.ReadKey().KeyChar
        If input = "y"c Or input = "Y"c Then
            For Each d As Double In results
                Console.Write("{0} ", d)
            Next
        End If

    End Sub
End Module

在此範例中示範的方法適用於迴圈執行最少量工作的情況。 當工作變得更運算密集時,藉由使用 ForForEach 迴圈與預設 Partitioner,您可能會取得相同或更高的效能。

另請參閱