Joan Venge
Joan Venge

Reputation: 331520

How to get the current time in a WPF game? (No XNA)

I am trying to make a small game like app that has some interaction, but need an accurate enough time to evaluate the game.

I saw some java versions using this method called System.nanoTime.

Is there a .NET version for it?

More importantly I am looking for a some sort of timer that I can use to evaluate the world. Should I be using an actual timer control and subscribe to it?

Also the game evaluates on a different thread than the UI thread. Just in case this makes a difference.

Upvotes: 7

Views: 6320

Answers (6)

codymanix
codymanix

Reputation: 29540

Use the StopWatch class, it uses QueryPerformanceCounter internally, so you have a very fine resolution. This way you do not need to pinvoke/interop.

Upvotes: 1

Dave White
Dave White

Reputation: 3461

DateTime.Now does not have an actual resolution in the nanosecond range. A Tick is a 100 nanosecond "chunk" of time but DateTime.Now does not resolve each Tick. I believe the lowest resolution for DateTime.Now is 10 milliseconds or so. If you call DateTime.Now twice very quickly, you'll get the same answer. You'll only see it tick up after about 10 milliseconds or so, depending on where in the cycle you are calling it.

The Stopwatch class has a finer resolution that DateTime.Now. I believe it will resolve down to the millisecond, which should hopefully give you enough resolution to determine if your game evaluation code is performing well enough. There is a great example that contrasts Stopwatch vs. DateTime at the link provided.

Also, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.

Upvotes: 5

Felix Martinez
Felix Martinez

Reputation: 3978

Have you tried

DateTime.Now;

This gives you the current time each time you call it. You could get it on two different points and subtract endtime - startime for timespan.

Upvotes: 3

taylonr
taylonr

Reputation: 10790

DateTime.Now.Ticks will get you down to 100 nanoseconds.

http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx

Upvotes: 1

Sam Axe
Sam Axe

Reputation: 33738

System.Threading.Timer has a 1ms resolution. If you need a higher resolution you can p/invoke QueryPerformanceFrequency() and QueryPerformanceCounter() in kernel32.dll

Upvotes: 4

Femaref
Femaref

Reputation: 61497

Well, there is DateTime.UtcNow or DateTime.Now. However, for recurring processes, you should use one of the timer classes. The one usually used for wpf is DispatcherTimer.

Upvotes: 1

Related Questions