gettimeofday的实现


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

使用c++实现就可以。




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM