There is an easy way to get a scaled unix timestamp in C ++

I am porting some PHP to C ++. Some of our database codes store time values ​​as timestamps. Unix * 100 Php contains code that looks something 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); } 

Something like this reasonable? Is there a tidier solution? Is there anything unpleasant in this code that I don't see? (Guess I'm not experienced enough with boost :: date_time to know these things)

+4
source share
3 answers

The solution suggested by dauphic could be changed to something like this

 uint64_t getTickTime() { timeval tim; gettimeofday(&tim, NULL); return tim.tv_sec*100 + tim.tv_usec/10000; } 

I can’t think of a more accurate solution than this.

+1
source

The most convenient and portable solution is to use the time() function defined in <ctime> , which returns the number of seconds from the Unix era.

If you use boost, you need universal_time() , not local_time() , since the era is specified in UTC.

+1
source

Assuming you are running Unix, enable <sys / time.h>

 timeval tim; gettimeofday(&tim, NULL); return tim.tv_usec; 

If on Windows there is no good way to get microsecond resolution, moreover, it uses a different era. Only <windows.h> is required for this sample, I suppose.

 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 
0
source

All Articles