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);
No, it’s not. Use the Stopwatch (in
System.Diagnostics)Stopwatch automatically checks for the existence of high-precision timers.
It is worth mentioning that
DateTime.Nowoften is quite a bit slower thanDateTime.UtcNowdue 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.Nowprecision for a great summary.Interesting trivia: The stopwatch falls back on
DateTime.UtcNowif 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.