Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

Elapsed time from start to finish with 20 ms precision

From this article http://blogs.msdn.com/b/ericlippert/archive/2010/04/08/precision-and-accuracy-of-datetime.aspx:

Now, the question “how much time has elapsed from start to finish?” is a completely different question than “what time is it right now?” If the question you want to ask is about how long some operation took, and you want a high-precision, high-accuracy answer, then use the StopWatch class. It really does have nanosecond precision and accuracy that is close to its precision.

The question is - what should I use if I need elapsed time from start to finish and I need 20 ms precision?

StopWatch has much better precision so I'm afraid that I will pay processor time for "extra-precision" which I don't need.

DateTime.Now has exactly precision I need but it also has a lot of extra-stuff like Month, Year etc. and I'm again afraid that this makes it much slower.

Upvotes: 2

Views: 228

Answers (3)

Răzvan Flavius Panda
Răzvan Flavius Panda

Reputation: 22116

From what I read on the internet untill now StopWatch class from System.Diagnostics namespace is the best class used for timing.

If you want precision under 1 ms remember to use the Elapsed.TotalMilliseconds property to retrieve elapsed time, sw.ElapsedMilliseconds jumps in increments of 1 ms.

using System;
using System.Diagnostics;

namespace MySolution
{
    class Program
    {
        static void Main(string[] args)
        {
            var sw = Stopwatch.StartNew();

            // code to be timed here

            sw.Stop();
            Console.WriteLine("Run time in ms = {0}", sw.Elapsed.TotalMilliseconds);
        }
    }
}

Upvotes: 0

user1088520
user1088520

Reputation:

The only (considerable?) overhead of the StopWatch is the incorporation of QueryPerformanceFrequency determining if the StopWatch will go on with high resolution frequency or not. Actually it is an overhead only if it will go without high resolution frequency. Otherwise is a faster option as it gets the timestamp with a WIN32 QueryPerformanceCounter call instead of DateTime.UtcNow.Ticks.

Upvotes: 1

LMW-HH
LMW-HH

Reputation: 1193

This article should help you:

http://www.dijksterhuis.org/timing-function-performance-stopwatch-class/

In general it says that the Stopwatch is the better choice, which is even my personal opinion.

Upvotes: 3

Related Questions