I want to get the most accurate (1ms accuracy will be very good) time of day.
I saw this example which is using GetLocalTime:
using System;
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public class SystemTime
{
public ushort year;
public ushort month;
public ushort weekday;
public ushort day;
public ushort hour;
public ushort minute;
public ushort second;
public ushort millisecond;
}
public class LibWrap
{
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime([In, Out] SystemTime st);
}
public class App
{
public static void Main()
{
SystemTime st = new SystemTime();
LibWrap.GetLocalTime(st);
Console.Write("{0}:{1}:{2}.{3}", st.hour, st.minute, st.second, st.millisecond);
Console.ReadKey();
}
}
how much it is accurate?
Most likely the timer accuracy. Which is 16ms by default(on newer versions of windows), and can be reduced to 1ms with
timeBeginPeriod(1)(potentially increasing power consumption of the computer).All “absolute time” functions on windows I know work at timer accuracy. So I expect it to be no better or worse than
DateTime.Now.Relative time functions (
StopWatch,QueryPerformanceCounter) have higher accuracy, but give you no meaningful absolute time. They can also suffer from synchronization issues across multiple CPU cores.But why don’t you test it: Write a small program that reads the time, and prints it whenever it increased. Do the same for
DateTime.Now. And compare.