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.
Example
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)
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
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.")
Console.ReadKey()
End Sub
static void Main()
{
var source = Enumerable.Range(0, 3000000);
var queryToMeasure = from num in source
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.
System.Diagnostics.Stopwatch sw = System.Diagnostics.Stopwatch.StartNew();
// For pure query cost, enumerate and do nothing else.
foreach (var n in queryToMeasure) { }
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.");
Console.ReadKey();
}
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.