在MFC下做開發,有時需要記錄當前系統時間,使用CTime保存時間,用函數GetCurrentTime()來獲取時間是個辦法。但是在MFC中有2個GetCurrentTime函數,一不留神就容易混淆。
CTime currentTime = GetCurrentTime();
CTime currentTime2 = CTime::GetCurrentTime();
GetCurrentTime()在文件winbase.h中,實際執行的是GetTickCount(),這是Windows API,用來返回從系統開機到現在間隔的毫秒數,超過49天之后,將會溢出。winbase.h中對該函數宏定義如下,建議采用GetTickCount64代替GetTickCount
Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.
#define GetCurrentTime() GetTickCount()
__drv_preferredFunction("GetTickCount64", "GetTickCount overflows roughly every 49 days. Code that does not take that into account can loop indefinitely. GetTickCount64 operates on 64 bit values and does not have that problem")
WINBASEAPI
DWORD
WINAPI
GetTickCount(
VOID
);
CTime::GetCurrentTime() 函數的定義在atltime.inl文件中,實際通過調用::_time64()函數來獲取時間
ATLTIME_INLINE CTime WINAPI CTime::GetCurrentTime() throw()
{
return( CTime( ::_time64( NULL ) ) );
}
::_time64在atltime.inl文件中定義如下,當傳入的指針為NULL時,只返回系統當前時間。
/***
*__time64_t _time64(timeptr) - Get current system time and convert to a
* __time64_t value.
*
*Purpose:
* Gets the current date and time and stores it in internal 64-bit format
* (__time64_t). The time is returned and stored via the pointer passed in
* timeptr. If timeptr == NULL, the time is only returned, not stored in
* *timeptr. The internal (__time64_t) format is the number of seconds
* since 00:00:00, Jan 1 1970 (UTC).
*
*Entry:
* __time64_t *timeptr - pointer to long to store time in.
*
*Exit:
* returns the current time.
*
*Exceptions:
*
*******************************************************************************/
__time64_t __cdecl _time64 (
__time64_t *timeptr
)
{
__time64_t tim;
FT nt_time;
GetSystemTimeAsFileTime( &(nt_time.ft_struct) );
tim = (__time64_t)((nt_time.ft_scalar - EPOCH_BIAS) / 10000000i64);
if (tim > _MAX__TIME64_T)
tim = (__time64_t)(-1);
if (timeptr)
*timeptr = tim; /* store time if requested */
return tim;
}
_time64() 實際上是調用GetSystemTimeAsFileTime()來獲取系統時間
GetSystemTimeAsFileTime函數在MSDN定義如下:
Retrieves the current system date and time. The information is in Coordinated Universal Time (UTC) format.
void WINAPI GetSystemTimeAsFileTime( _Out_ LPFILETIME lpSystemTimeAsFileTime );
typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME, *PFILETIME;
FILETIME相當於一個64位整型數,到這里就可以看出,雖然兩個函數同名,但是時間上返回的時間值是不一樣。
GetCurrentTime() 返回的是距離系統啟動時的微秒數
CTime::GetCurrentTime() 才是返回的當前系統時間