Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Porting clock_gettime to windows

Tags:

c++

c

windows

I have the following code running on qnx momemntics.

#define BILLION 1000000000L;  struct timespec start_time; struct timespec stop_time;   void start MyTestFunc() {     //Initialize the Test Start time      clock_gettime(CLOCK_REALTIME,&start_time)     // ... additonal code.      cout << "The exectuion time of func "<< calculateExecutionTime(); }   double calculateExecutionTime () {      clock_gettime(CLOCK_REALTIME,&stop_time);      double dSeconds = (stop_time.tv_sec - start_time.tv_sec);      double dNanoSeconds = (double)( stop_time.tv_nsec - start_time.tv_nsec ) / BILLION;      return dSeconds + dNanoSeconds; } 

Now i want to port above code to windows. can any one provide sample code.

Thanks!

like image 410
venkysmarty Avatar asked Mar 23 '11 11:03

venkysmarty


1 Answers

You can implement a clock_gettime() replacement for windows as follows:

LARGE_INTEGER getFILETIMEoffset() {     SYSTEMTIME s;     FILETIME f;     LARGE_INTEGER t;      s.wYear = 1970;     s.wMonth = 1;     s.wDay = 1;     s.wHour = 0;     s.wMinute = 0;     s.wSecond = 0;     s.wMilliseconds = 0;     SystemTimeToFileTime(&s, &f);     t.QuadPart = f.dwHighDateTime;     t.QuadPart <<= 32;     t.QuadPart |= f.dwLowDateTime;     return (t); }  int clock_gettime(int X, struct timeval *tv) {     LARGE_INTEGER           t;     FILETIME            f;     double                  microseconds;     static LARGE_INTEGER    offset;     static double           frequencyToMicroseconds;     static int              initialized = 0;     static BOOL             usePerformanceCounter = 0;      if (!initialized) {         LARGE_INTEGER performanceFrequency;         initialized = 1;         usePerformanceCounter = QueryPerformanceFrequency(&performanceFrequency);         if (usePerformanceCounter) {             QueryPerformanceCounter(&offset);             frequencyToMicroseconds = (double)performanceFrequency.QuadPart / 1000000.;         } else {             offset = getFILETIMEoffset();             frequencyToMicroseconds = 10.;         }     }     if (usePerformanceCounter) QueryPerformanceCounter(&t);     else {         GetSystemTimeAsFileTime(&f);         t.QuadPart = f.dwHighDateTime;         t.QuadPart <<= 32;         t.QuadPart |= f.dwLowDateTime;     }      t.QuadPart -= offset.QuadPart;     microseconds = (double)t.QuadPart / frequencyToMicroseconds;     t.QuadPart = microseconds;     tv->tv_sec = t.QuadPart / 1000000;     tv->tv_usec = t.QuadPart % 1000000;     return (0); } 
like image 130
Carl Staelin Avatar answered Sep 23 '22 00:09

Carl Staelin