Get the current system time (microseconds)

Get the current time of the system

When debugging, log output, and code optimization, we often need to obtain system time. In some code optimizations with high performance requirements, the accuracy of the time is still relatively high. I couldn't find high-quality code on the Internet, so I researched it myself. The code is as follows (which can meet the requirements of cross-platform, the unit is accurate to microseconds):

#ifdef _WIN32
#include <windows.h>
#else
#include <time.h>
#endif  // _WIND32


// 定义64位整形
#if defined(_WIN32) && !defined(CYGWIN)
typedef __int64 int64_t;
#else
typedef long long int64t;
#endif  // _WIN32

// 获取系统的当前时间,单位微秒(us)
int64_t GetSysTimeMicros()
{
#ifdef _WIN32
// 从1601年1月1日0:0:0:000到1970年1月1日0:0:0:000的时间(单位100ns)
#define EPOCHFILETIME   (116444736000000000UL)
    FILETIME ft;
    LARGE_INTEGER li;
    int64_t tt = 0;
    GetSystemTimeAsFileTime(&ft);
    li.LowPart = ft.dwLowDateTime;
    li.HighPart = ft.dwHighDateTime;
    // 从1970年1月1日0:0:0:000到现在的微秒数(UTC时间)
    tt = (li.QuadPart - EPOCHFILETIME) /10;
    return tt;
#else
    timeval tv;
    gettimeofday(&tv, 0);
    return (int64_t)tv.tv_sec * 1000000 + (int64_t)tv.tv_usec;
#endif // _WIN32
    return 0;
}

Code description

Use the gettimeofday method on Unix-like platforms (Linux, OS-X), this is simple, there is nothing to say, look at the code yourself. Use the GetSystemTimeAsFileTime method on the Windows platform, this needs to be explained.

The output parameter of GetSystemTimeAsFileTime is LPFILETIME, and its structure is as follows:

typedef struct _FILETIME {
   DWORD dwLowDateTime;
   DWORD dwHighDateTime; 
} FILETIME, *PFILETIME;

This structure can be expressed as a 64-bit value, and the two become the lower 32 bits and the upper 32 bits of the code respectively, representing the counter from January 1, 1601 to the present, and the counting interval is 100 nanoseconds. 
and

li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;

Is to convert the structure into a 64-bit integer LARGE_INTEGER::QuadPart. 
#define EPOCHFILETIME (116444736000000000UL) represents the time from 0:0:0:000 on January 1, 1601 to 0:0:0:000 on January 1, 1970 (in 100ns).

Guess you like

Origin blog.csdn.net/wyyy2088511/article/details/108733309