This documentation is archived and is not being maintained.

How to: Measure PLINQ Query Performance

This example shows how use the Stopwatch class to measure the time it takes for a PLINQ query to execute.

This example uses an empty foreach loop (For Each in Visual Basic) to measure the time it takes for the query to execute. In real-world code, the loop typically contains additional processing steps that add to the total query execution time. Notice that the stopwatch is not started until just before the loop, because that is when the query execution begins. If you require more fine-grained measurement, you can use the ElapsedTicks property instead of ElapsedMilliseconds.

Sub Main()
    Dim source = Enumerable.Range(0, 3000000)
    Dim queryToMeasure = From num In source
                         Where num Mod 3 = 0
                         Select Math.Sqrt(num)


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

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

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

    ' Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit.")
End Sub

The total execution time is a useful metric when you are experimenting with query implementations, but it does not always tell the whole story. To get a deeper and richer view of the interaction of the query threads with one another and with other running processes, use the Concurrency Visualizer. This tool is available in Microsoft Visual Studio 2010 Premium. For more information, see Concurrency Visualizer.