0

I want to get the local time in real time.The code and result is as follow, it showed strange;

int main() {
    while (true) {
        char sentdata[64] = { 0 };
        GetLocalTime(&sys);
        sprintf(sentdata, "A,%02d:%02d:%02d.%03d,B\n", sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds);

        cout << sentdata << endl;
    }
    return 0;
}

enter image description here

I tried same code on other PC, the result shown is as following, it can show every millisecond.

enter image description here

Why the tmie is same in some loop? I think the time should be different every loop.

Ajay
  • 18,086
  • 12
  • 59
  • 105
kookoo121
  • 1,116
  • 2
  • 12
  • 21
  • 2
    Clock updates are synchronous with the clock tick interrupt. Which fires 64 times per second by default. 1000 / 64 = 15.625, just what you see. It can be messed with, timeBeginPeriod(). – Hans Passant Nov 12 '15 at 08:03
  • @HansPassant Thank you for your comment.But i tried the same code on another pc , i can get every millisecond as the pic i have updated,not 16 milliseconds one update,why? – kookoo121 Nov 12 '15 at 12:23
  • I already told you. Expecting to see every single millisecond pass by is mostly a pipe dream on a multi-tasking operating system. Although you can technically lock it down to ensure no other processes can get started and troublemaker drivers are disabled so your thread is never pre-empted. Technically. – Hans Passant Nov 12 '15 at 12:29
  • @HansPassant But you can see the pic2 i have upload, i just use the same code on another pc and i can see every millisecond. – kookoo121 Nov 12 '15 at 12:35
  • Regarding your second PC, the heartbeat may be increased beyond the typical 64 beats/second rate, but I can't tell you why. See here for further details: https://randomascii.wordpress.com/2013/07/08/windows-timer-resolution-megawatts-wasted/ – Daniel Strul Nov 12 '15 at 13:07
  • 1
    Starting up Chrome is a pretty good way to get another program to call timeBeginPeriod(1) for you. – Hans Passant Nov 12 '15 at 13:12

2 Answers2

5

This a typical timing behavior on Windows systems, even with the high-resolution clock: time only increases in jumps of about 16 ms.

For accurate timing on Windows, see this answer

Community
  • 1
  • 1
Daniel Strul
  • 1,458
  • 8
  • 16
1

Your code runs in nanoseconds, while the output is in milliseconds.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33