방법: PLINQ 쿼리 성능 측정

다음 예제에서는 Stopwatch 클래스를 사용하여 PLINQ 쿼리를 실행하는 데 걸리는 시간을 측정하는 방법을 보여 줍니다.

예시

이 예제에서는 빈 foreach 루프(Visual Basic에서 For Each)를 사용하여 쿼리를 실행하는 데 걸리는 시간을 측정합니다. 실제 코드에서 루프는 일반적으로 전체 쿼리 실행 시간에 추가되는 추가 처리 단계를 포함합니다. 루프 바로 전까지 스톱워치를 시작하지 않습니다. 루프 바로 전은 쿼리 실행을 시작하는 시점이기 때문입니다. 보다 세밀한 측정이 필요한 경우 ElapsedMilliseconds 대신 ElapsedTicks 속성을 사용할 수 있습니다.

using System;
using System.Diagnostics;
using System.Linq;

class ExampleMeasure
{
    static void Main()
    {
        var source = Enumerable.Range(0, 3000000);

        var queryToMeasure =
             from num in source.AsParallel()
             where num % 3 == 0
             select Math.Sqrt(num);

        Console.WriteLine("Measuring...");

        // The query does not run until it is enumerated.
        // Therefore, start the timer here.
        var sw = Stopwatch.StartNew();

        // For pure query cost, enumerate and do nothing else.
        foreach (var n in queryToMeasure) { }

        sw.Stop();
        long elapsed = sw.ElapsedMilliseconds; // or sw.ElapsedTicks
        Console.WriteLine("Total query time: {0} ms", elapsed);

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
Module ExampleMeasure
    Sub Main()
        Dim source = Enumerable.Range(0, 3000000)
        ' Define parallel and non-parallel queries.
        Dim queryToMeasure = From num In source.AsParallel()
                             Where num Mod 3 = 0
                             Select Math.Sqrt(num)

        Console.WriteLine("Measuring...")

        ' The query does not run until it is enumerated.
        ' Therefore, start the timer here.
        Dim sw = Stopwatch.StartNew()

        ' For pure query cost, enumerate and do nothing else.
        For Each n As Double In queryToMeasure
        Next

        sw.Stop()
        Dim elapsed As Long = sw.ElapsedMilliseconds  ' or sw.ElapsedTicks
        Console.WriteLine($"Total query time: {elapsed} ms.")

        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub
End Module

쿼리 구현을 실험하는 경우 총 실행 시간은 유용한 메트릭이지만 항상 전체적인 내용을 알려주지는 않습니다. 쿼리 스레드 간의 상호 작용 또는 다른 실행 중인 프로세스와 쿼리 스레드의 상호 작용을 자세히 보려면 동시성 시각화 도우미를 사용합니다.

참고 항목