方案一:
#include <time.h>
#ifdef WIN32
# ? include <windows.h>
#else
# ? include <sys/time.h>
#endif
#ifdef WIN32
int
gettimeofday(struct timeval *tp, void *tzp)
{
? ? time_t clock;
? ? struct tm tm;
? ? SYSTEMTIME wtm;
? ? GetLocalTime(&wtm);
? ? tm.tm_year ? ? = wtm.wYear - 1900;
? ? tm.tm_mon ? ? = wtm.wMonth - 1;
? ? tm.tm_mday ? ? = wtm.wDay;
? ? tm.tm_hour ? ? = wtm.wHour;
? ? tm.tm_min ? ? = wtm.wMinute;
? ? tm.tm_sec ? ? = wtm.wSecond;
? ? tm. tm_isdst ? ?= -1;
? ? clock = mktime(&tm);
? ? tp->tv_sec = clock;
? ? tp->tv_usec = wtm.wMilliseconds * 1000;
? ? return (0);
}
#endif
?
方案二:
gettimeofday的使用
//copy from muduo Timestamp Timestamp::now() {struct timeval tv;gettimeofday(&tv, NULL);//返回1970年至今的秒+微秒int64_t seconds = tv.tv_sec;return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec); }
gettimeofday要求傳入一個timeval和一個時區。因為存在微秒數,顯然它比 time_t now = ::time(NULL)更精確。
但是這個函數是linux下的。所以我們需要一個跨平臺的實現。
以下是一個實現,使用c++的chrono庫。
#include <chrono> int gettimeofday(struct timeval *__restrict __tv, __timezone_ptr_t __tz) { auto now = std::chrono::system_clock::now(); auto now_ticks = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());// __tv->tv_sec = (long)now_ticks.count() / 1000000; __tv->tv_usec = (long)now_ticks.count() % 1000000; return 0; }
now.time_since_epoch()返回的duration比較奇怪,需要轉化成微秒。其實主要是windows沒有這個函數,那么我們實現它。
//copy from evpp #ifdef WIN32 int gettimeofday(struct timeval* tp, void* tzp) {uint64_t intervals;FILETIME ft;GetSystemTimeAsFileTime(&ft);/** A file time is a 64-bit value that represents the number* of 100-nanosecond intervals that have elapsed since* January 1, 1601 12:00 A.M. UTC.** Between January 1, 1970 (Epoch) and January 1, 1601 there were* 134744 days,* 11644473600 seconds or* 11644473600,000,000,0 100-nanosecond intervals.** See also MSKB Q167296.*/intervals = ((uint64_t)ft.dwHighDateTime << 32) | ft.dwLowDateTime;intervals -= 116444736000000000;tp->tv_sec = (long)(intervals / 10,000,000);tp->tv_usec = (long)((intervals % 10000000) / 10);return (0); }
?
?
?
?
?