views:

325

answers:

3

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? Is 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)

+1  A: 

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.

Mike Seymour
time only returns seconds. I need at least hundredths of a second.
Michael Anderson
A: 

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
dauphic
gettimeofday may work for me. But not as you've presented it, as that returns only the microseconds since the last second. I'm on a unixy system so a windows solution is no good.
Michael Anderson
A: 

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.

Michael Anderson