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.

Module Example
    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 = System.Diagnostics.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: {0} ms.", elapsed)

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

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. For more information, see Concurrency Visualizer.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft