Is there a simple way to get scaled unix timestamp in C++
I'm porting some PHP to C++. Some of our database code stores time values as unix time stamps *100 The php contains code that looks a bit like this.
//PHP
static function getTickTime()
{
return round(microtime(true)*100);
}
I need something like this:
//C++
uint64_t getTickTime()
{
ptime Jan1st1970(date(1970, 1, 1));
ptime Now = microsecond_clock::local_time();
time_duration diff = Now - Jan1st1970;
return static_cast<uint64_t>(diff.total_seconds()*100);
}
Is something like this sensible? I开发者_高级运维s there a neater solution? Is there something nasty in this code that I can't see? (Guess I'm not experienced enough with boost::date_time to know these things)
The neatest and most portable solution is to use the time()
function, defined in <ctime>
, which returns the number of seconds since the Unix epoch.
If you do use boost, you'll want universal_time()
, not local_time()
, since the epoch is specified in UTC.
The solution suggested by dauphic can be modified to something like this
uint64_t getTickTime()
{
timeval tim;
gettimeofday(&tim, NULL);
return tim.tv_sec*100 + tim.tv_usec/10000;
}
I cant think of a neater solution than that.
Assuming you're on Unix, include <sys/time.h>
timeval tim;
gettimeofday(&tim, NULL);
return tim.tv_usec;
If on Windows, there's no good way to get microsecond resolution, especially because it uses a different epoch. This sample requires only <windows.h> I believe.
FILETIME tim;
GetSystemTimeAsFileTime(&tim);
ULARGE_INTEGER ms;
ms.LowPart = tim.dwLowDateTime;
ms.HighPart = tim.dwHighDateTime;
return ms.QuadPart * 10 + <nanoseconds from January 1, 1609 to January 1, 1970>; // ms represents how many 100s of nanoseconds
精彩评论