C在Windows上获得微秒精度的系统时间?

Dan*_*iel 9 c c++ windows

可能重复:
在c ++中以微秒的分辨率测量时间?

嗨,

有没有一种简单的方法可以在Windows机器上获得系统时间,精确到微秒?

Art*_*yom 10

看看GetSystemTimeAsFileTime

它为您提供0.1微秒或100纳秒的精度.

请注意,它的Epoch与POSIX Epoch不同.

因此,要获得POSIX时间(以微秒为单位),您需要:

    FILETIME ft;
    GetSystemTimeAsFileTime(&ft);
    unsigned long long tt = ft.dwHighDateTime;
    tt <<=32;
    tt |= ft.dwLowDateTime;
    tt /=10;
    tt -= 11644473600000000ULL;
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下 time(0) == tt / 1000000

  • 来自`KeQuerySystemTime`:"系统时间通常大约每十毫秒更新一次." (6认同)
  • 更可能是以100纳秒而不是100纳秒精度表示的时间? (3认同)

Dar*_*ara 4

像这样

unsigned __int64 freq;
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
double timerFrequency = (1.0/freq);

unsigned __int64 startTime;
QueryPerformanceCounter((LARGE_INTEGER *)&startTime);

//do something...

unsigned __int64 endTime;
QueryPerformanceCounter((LARGE_INTEGER *)&endTime);
double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency);
Run Code Online (Sandbox Code Playgroud)

  • QueryPerformanceCounter 不返回**系统时间**,而是返回高分辨率**计数器**。 (6认同)