For() 루프의 본문 크기가 작은 경우에는 그에 상응하는 순차 루프를 사용할 때보다 실행 속도가 느릴 수 있습니다. 이는 데이터를 분할할 때 오버헤드가 발생하고 각 루프 반복에서 대리자를 호출해야 하기 때문입니다. 이와 같은 시나리오를 해결하기 위해 Partitioner 클래스에서는 Create 메서드를 제공합니다. 이 메서드를 사용하면 대리자 본문에 대한 순차 루프를 제공하여 대리자를 반복별로 한 번씩 호출하는 대신 파티션별로 한 번씩만 호출하게 할 수 있습니다. 자세한 내용은 PLINQ 및 TPL에 대한 사용자 지정 파티셔너를 참조하십시오.
예제
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
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);
}
}
}
}
이 예제에서 보여 주는 방법은 루프에서 최소한의 작업을 수행하는 경우에 유용합니다. 작업에 많은 계산 과정이 필요하게 될 경우에는 기본 파티셔너가 있는 For 또는 ForEach 루프를 사용하는 편이 성능 향상에 도움이 될 수 있습니다.