Get System Current Time
When debugging, log output, and code optimization, we often need to get the system time. In some performance-demanding code optimization, the accuracy of time is also relatively high. On the internet to find a high-quality code, they have studied, the code is as follows (to meet cross-platform requirements, units accurate to microseconds):
#ifdef _WIN32#include <windows.h>#else#include <time.h>#endif//_WIND32Defining 64-bit shaping#if defined (_WIN32) &&!defined (CYGWIN) typedef __int64 int64_t;#elsetypedefLongLong int64t;#endif//_win32Gets the current time of the system, in microseconds (US) int64_t Getsystimemicros () {#ifdef _WIN32//from January 1, 1601 0:0:0:000 to January 1, 1970 0:0:0:000 Time (unit 100ns) #define EPOCHFILETIME (116444736000000000UL) FILETIME Ft Large_integer li; int64_t tt = 0; Getsystemtimeasfiletime (&ft); Li. LowPart = Ft.dwlowdatetime; Li. Highpart = Ft.dwhighdatetime; //from January 1, 1970 0:0:0:000 to present microseconds (UTC time) 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
Using the Gettimeofday method on Unix-like platforms (Linux, os-x), this simple, nothing to say, look at the code yourself. Using the Getsystemtimeasfiletime method on the Windows platform, this needs to be explained.
The output parameter of the getsystemtimeasfiletime is Lpfiletime, which is structured as follows:
typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME, *PFILETIME;
This structure can be represented as a 64-bit numeric value, and the two become 32-bit low and 32-bit high, representing the counter starting January 1, 1601 to the present, with a count interval of 100 nanoseconds.
and
li.LowPart = ft.dwLowDateTime;li.HighPart = ft.dwHighDateTime;
is to convert the structure into 64-bit shaping Large_integer::quadpart.
#define EPOCHFILETIME (116444736000000000UL) represents the time from January 1, 1601 0:0:0:000 to January 1, 1970 0:0:0:000 (unit 100ns).
C + + Gets the current time of the system (accurate to microseconds)