操作說明:測量 PLINQ 查詢效能

這個範例示範如何使用 Stopwatch 類別,測量執行 PLINQ 查詢所需的時間。

範例

這個範例會使用空的 foreach 迴圈 (在 Visual Basic 中為 For Each) 來測量執行查詢所需的時間。 在真實的程式碼中,迴圈通常包含會增加查詢執行總時間的額外處理步驟。 請注意,碼錶不會在迴圈之前啟動,因為迴圈就是執行查詢開始的時間。 如果您需要更精細的測量,您可以使用 ElapsedTicks 屬性而非 ElapsedMilliseconds

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

當您試驗查詢實作時,總執行時間是很有用的計量,但不一定能反映全貌。 若要取得查詢執行緒彼此之間以及與其他執行中處理序的更深入、更豐富互動檢視,請使用 [並行視覺化檢視]

另請參閱