-1

I've seen lots of questions about high precision timers in windows, but what I really need is something that gives me the clock time in windows that's more accurate than the 10-15ms granularity GetLocalTime() offers.

I couldn't find any existing and simple solution so I came up with one of my own, not completely flushed out, but the basic idea works until midnight. Sharing it here so it can be helpful to others.

Store an anchor time when the program starts and use timeGetTime() to get the system uptime in ms (which is granular to less than 1 ms) and adjust the anchortime accordingly.

Code is in the answer.

4

1 回答 1

-1

First time you run it, it gets the time and the tickcount so they're in sync and we have something to measure by. The init section isn't threadsafe and it doesn't wrap over midnight, but that's easily added by following the carry form below....

// this solution is limited to 49+ days of uptime
int timeinitted = 0;
SYSTEMTIME anchortime;
DWORD anchorticks; 

void GetAccurateTime(SYSTEMTIME *lt)
  {
    if (timeinitted == 0)
      { // obviously this init section isn't threadsafe. 
        // get an anchor time to sync up with system ticks. 
        GetLocalTime(&anchortime);
        anchorticks = timeGetTime();
        timeinitted = 1;
      }

     DWORD now = timeGetTime();
     DWORD flyby = now - anchorticks;

     // now add flyby to anchortime
     memcpy (lt, &anchortime, sizeof(anchortime));
     // you can't do the math IN the SYSTEMTIME because everything in it is a WORD (16 bits)
     DWORD ms = lt->wMilliseconds + flyby;
     DWORD carry = ms / 1000;
     lt->wMilliseconds = ms % 1000;
     if (carry > 0)
       {
         DWORD s = lt->wSecond + carry;
         carry = s / 60;
         lt->wSecond = s % 60;
         if (carry > 0)
           {
             DWORD m = lt->wMinute + carry;
             carry = m / 60;
             lt->wMinute = m % 60;
             if (carry > 0) // won't wrap day correctly.
               lt->wHour = (((DWORD)lt->wHour + carry)) % 24;
           }
         // add day and month and year here if you're so inspired, but remember the 49 day limit
       }
  }
于 2012-11-14T18:23:56.717 回答