Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

wpf

timer

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.

like image 967
Joan Venge Avatar asked Apr 07 '11 20:04

Joan Venge


1 Answers

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.

like image 98
Dave White Avatar answered Oct 03 '22 14:10

Dave White