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.

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

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