C# – Exact time measurement for performance testing


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?

Best Solution

A better way is to use the Stopwatch class:

using System.Diagnostics;
// ...

Stopwatch sw = new Stopwatch();


// ...