C 在 Windows 上获取系统时间到微秒精度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4568221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:46:14  来源:igfitidea点击:

C get system time to microsecond accuracy on windows?

c++cwindows

提问by Daniel

Possible Duplicate:
measuring time with resolution of microseconds in c++?

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

Hi,

你好,

Is there a simple way i can get the system time on a Windows machine, down to microsecond accuracy?

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

回答by Artyom

Look at GetSystemTimeAsFileTime

查看 GetSystemTimeAsFileTime

It gives you accuracy in 0.1 microseconds or 100 nanoseconds.

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

Note that it's Epoch different from POSIX Epoch.

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

So to get POSIX time in microseconds you need:

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

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

So in such case time(0) == tt / 1000000

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

回答by Darcara

Like this

像这样

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);

回答by user541686

What we really need is a high-resolution GetTickCount(). As far as I know, this doesn't really exist.

我们真正需要的是高分辨率的GetTickCount(). 据我所知,这实际上并不存在。

If you're willing to use a hackish way to solve this (that would probably only work on some versions of Windows like XP), look here at ReactOS. Then try this code:

如果您愿意使用一种骇人听闻的方式来解决这个问题(这可能仅适用于某些版本的 Windows,如 XP),请查看ReactOS。然后试试这个代码:

long long GetTickCount64()
{
    return (long long)
        ((((unsigned long long)*(unsigned long int*)0x7FFE0000
           * (unsigned long long)*(unsigned long int*)0x7FFE0004)
         * (unsigned long long)10000) >> 0x18);
}

Tweaking it might give you what you need in some versions of Windows.

调整它可能会在某些版本的 Windows 中为您提供所需的内容。