DateTime.Now
は精度が 10 msec 程度。より正確な時刻がほしいときに使う。時間であれば Stopwatch
クラスがじゅうぶんに高精度(High-Resolution Timer 精度)。
[DllImport("kernel32.dll")]
private static extern void GetSystemTimePreciseAsFileTime(out long filetime);
public DateTime GetSystemTimeAsDate()
{
long fileTime;
GetSystemTimePreciseAsFileTime(out fileTime);
return DateTime.FromFileTimeUtc(fileTime).ToLocalTime();
}
参考:GetSystemTimePreciseAsFileTime function
蛇足(背景):Wireshark の測定結果とアプリのログを付き合わせようとしたら、アプリ側の時刻がガバガバで何も得られなかったので、高精度な時刻がほしいなあとWiresharkのソース を読んでいたら以下のようなコメントがあった。
dumpcap.c
#ifdef _WIN32
/*
* Current time, represented as 100-nanosecond intervals since
* January 1, 1601, 00:00:00 UTC.
*
* I think DWORD might be signed, so cast both parts of "now"
* to guint32 so that the sign bit doesn't get treated specially.
*
* Windows 8 provides GetSystemTimePreciseAsFileTime which we
* might want to use instead.
*/
GetSystemTimeAsFileTime(&now);