i want to have a time stamp for logs on a Windows Mobile project. The accuracy must be in the range a hundred milliseconds at least.
However my call to DateTime.Now
returns a DateTime
object with the Millisecond
property set to zero. Also the Ticks
property is rounded accordingly.
How to get better time accuracy?
Remember, that my code runs on on the Compact Framework, version 3.5. I use a HTC touch Pro 2 device.
Based on the answer from MusiGenesis i have created the following class which solved this problem:
/// <summary>
/// A more precisely implementation of some DateTime properties on mobile devices.
/// </summary>
/// <devdoc>Tested on a HTC Touch Pro2.</devdoc>
public static class DateTimePrecisely
{
/// <summary>
/// Remembers the start time when this model was created.
/// </summary>
private static DateTime _start = DateTime.Now;
/// <summary>
/// Remembers the system uptime ticks when this model was created. This
/// serves as a more precise time provider as DateTime.Now can do.
/// </summary>
private static int _startTick = Environment.TickCount;
/// <summary>
/// Gets a DateTime object that is set exactly to the current date and time on this computer, expressed as the local time.
/// </summary>
/// <returns></returns>
public static DateTime Now
{
get
{
return _start.AddMilliseconds(Environment.TickCount - _startTick);
}
}
}
To get the milliseconds only of the current time, we use the "Millisecond" property of the DateTime class in C#. We use the "Millisecond" property with the object of DateTime class which should be initialized with the current date-time i.e. "Now".
It tends to be between 0.5 and 15 milliseconds. As a result, repeated calls to the Now property in a short time interval, such as in a loop, may return the same value.
NET Compact Framework has the biggest challenges are graphics, window management, and resource management.
Environment.TickCount
will return the number of milliseconds that Windows (or Windows Mobile) has been running since the last reboot.
To use this, add these two form-level variables to your code:
private DateTime _start;
private int _startTick;
In your form's Load event, do this:
private void Form1_Load(object sender, EventArgs e)
{
_start = DateTime.Now;
_startTick = Environment.TickCount;
}
Whenever you need a DateTime object with milliseconds, do this:
DateTime timeStamp =
_start.AddMilliseconds(Environment.TickCount - _startTick);
Environment.TickCount
is an int
and this value will "wrap around" to Int32.MinValue
after 25 days or so. If your device is going to be running that long without restarting, you'll want to add a check for an Environment.TickCount
value that is less than the last value read, and reset both _start
and _startTick
if so.
What about the High Resolution Timer?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With