Is DateTime.Now the best way to measure a function's performance? [closed]

I need to find a bottleneck and need to accurately as possible measure time.

Is the following code snippet the best way to measure the performance?

DateTime startTime = DateTime.Now;

// Some execution process

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);

Solution 1:

No, it's not. Use the Stopwatch (in System.Diagnostics)

Stopwatch sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds);

Stopwatch automatically checks for the existence of high-precision timers.

It is worth mentioning that DateTime.Now often is quite a bit slower than DateTime.UtcNow due to the work that has to be done with timezones, DST and such.

DateTime.UtcNow typically has a resolution of 15 ms. See John Chapman's blog post about DateTime.Now precision for a great summary.

Interesting trivia: The stopwatch falls back on DateTime.UtcNow if your hardware doesn't support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field Stopwatch.IsHighResolution.

Solution 2:

If you want something quick and dirty I would suggest using Stopwatch instead for a greater degree of precision.

Stopwatch sw = new Stopwatch();
sw.Start();
// Do Work
sw.Stop();

Console.WriteLine("Elapsed time: {0}", sw.Elapsed.TotalMilliseconds);

Alternatively, if you need something a little more sophisticated you should probably consider using a 3rd party profiler such as ANTS.

Solution 3:

This article says that first of all you need to compare three alternatives, Stopwatch, DateTime.Now AND DateTime.UtcNow.

It also shows that in some cases (when performance counter doesn't exist) Stopwatch is using DateTime.UtcNow + some extra processing. Because of that it's obvious that in that case DateTime.UtcNow is the best option (because other use it + some processing)

However, as it turns out, the counter almost always exists - see Explanation about high-resolution performance counter and its existence related to .NET Stopwatch?.

Here is a performance graph. Notice how low performance cost UtcNow has compared to alternatives:

Enter image description here

The X axis is sample data size, and the Y axis is the relative time of the example.

One thing Stopwatch is better at is that it provides higher resolution time measurements. Another is its more OO nature. However, creating an OO wrapper around UtcNow can't be hard.