Exact time measurement for performance testing

Svish picture Svish · Jun 9, 2009 · Viewed 243.1k times · Source

What is the most exact way of seeing how long something, for example a method call, took in code?

The easiest and quickest I would guess is this:

DateTime start = DateTime.Now;
{
    // Do some work
}
TimeSpan timeItTook = DateTime.Now - start;

But how exact is this? Are there better ways?

Answer

Philippe Leybaert picture Philippe Leybaert · Jun 9, 2009

A better way is to use the Stopwatch class:

using System.Diagnostics;
// ...

Stopwatch sw = new Stopwatch();

sw.Start();

// ...

sw.Stop();

Console.WriteLine("Elapsed={0}",sw.Elapsed);