Search code examples
c#timemilliseconds

Get milliseconds passed


A just need a stable count of the current program's progression in milliseconds in C#. I don't care about what timestamp it goes off of, whether it's when the program starts, midnight, or the epoch, I just need a single function that returns a stable millisecond value that does not change in an abnormal manner besides increasing by 1 each millisecond. You'd be surprised how few comprehensive and simple answers I could find by searching.

Edit: Why did you remove the C# from my title? I'd figure that's a pretty important piece of information.


Solution

  • When your program starts create a StopWatch and Start() it.

    private StopWatch sw = new StopWatch();
    
    public void StartMethod()
    {
      sw.Start();
    }
    

    At any point you can query the Stopwatch:

    public void SomeMethod()
    {
      var a = sw.ElapsedMilliseconds;
    }
    

    If you want something accurate/precise then you need to use a StopWatch, and please read Eric Lippert's Blog (formerly the Principal Developer of the C# compiler Team) Precision and accuracy of DateTime.

    Excerpt:

    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.

    If you don't need an accurate time, and you don't care about precision and the possibility of edge-cases that cause your milliseconds to actually be negative then use DateTime.