Maurdekye
Maurdekye

Reputation: 3677

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.

Upvotes: 0

Views: 832

Answers (4)

Erik Philips
Erik Philips

Reputation: 54628

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.

Upvotes: 1

Icemanind
Icemanind

Reputation: 48686

It sounds like you are just trying to get the current date and time, in milliseconds. If you are just trying to get the current time, in milliseconds, try this:

long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;

Upvotes: 0

BoldAsLove
BoldAsLove

Reputation: 689

You could store the current time in milliseconds when the program starts, then in your function get the current time again and subtract

edit:

if what your going for is a stable count of process cycles, I would use processor clocks instead of time.

as per your comment you can use DateTime.Ticks, which is 1/10,000 of a millisecond per tick

Also, if you wanted to do the time thing you can use DateTime.Now as your variable you store when you start your program, and do another DateTime.Now whenever you want the time. It has a millisecond property.

Either way DateTime is what your looking for

Upvotes: 0

Blindy
Blindy

Reputation: 67380

Do you mean DateTime.Now? It holds absolute time, and subtracting two DateTime instances gives you a TimeSpan object which has a TotalMilliseconds property.

Upvotes: 0

Related Questions