LoginSignup
5
3

More than 5 years have passed since last update.

Windowsで精密な時刻を取得する(Windows8以降)

Posted at

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);
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3