简体   繁体   中英

C++ chrono micro-/nanoseconds not working

Edit: Chuck Walbourn's answer solved my problem. Working code is added at the bottom!

I am trying to calculate the time difference (smaller than millisec.) using the chrono lib, but I get very strange/inaccurate results. Also if I try "sleep_for" with values smaller than 1 ms (1000 us / 1000000 ns), the program sleeps for 1ms exactly.

My code:

#include <iostream>
#include <chrono>

int main() {
    auto start = std::chrono::high_resolution_clock::now();

    for (int i = 0; i < 100; i++)
    {
        auto finish = std::chrono::high_resolution_clock::now();
        std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(finish - start).count() << std::endl;
    }
}

My output:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1000000
1000000
1000000
1000000
1000000
2000100
2000100
2000100
3000100
3000100
4000200
4000200
5000200
5000200
6000300
6000300
7000400
7000400
8000400
8000400
9000500
9000500
10000500
10000500
11000600
11000600
12000600
12000600
12000600
13000700
13000700
14000800
14000800
15000800
15000800
15000800
16000900
16000900
17000900
17000900
18001000
18001000
19001000
19001000
19001000
20001100
20001100
21001200
21001200
22001200
22001200
23001300
23001300
23001300
24001300
24001300
25001400
25001400
26001400
26001400
27001500
27001500
28001600
28001600
29001600
29001600
29001600
30001700
30001700
31001700
31001700
32001800
32001800
32001800
33001800
33001800
34001900
34001900
35002000
35002000
36002000
36002000
37002100
Druk op een toets om door te gaan. . .

It obviously only increments in 1 milliseconds, but that still doesn't explain the random hunderd added sometimes. Can someone help me out here :(

I'm running Visual Studio 2013 and Windows 7

Added working code:

#include <iostream>
#include <chrono>
#include <Windows.h>

LARGE_INTEGER freq;
LARGE_INTEGER t1, t2;

long elapsedTime;

int main() {
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&t1);

    for (int i = 0; i < 100; i++)
    {
        QueryPerformanceCounter(&t2);
        elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000000000 / freq.QuadPart;
        std::cout << elapsedTime << std::endl;
    }
}

In VS 2012 and 2013, the high_resolution_clock is based on system time which has a resolution of 1 ms. In VS 2015, high_resolution_clock has been properly updated to use QueryPerformanceCounter so it has the expected high resolution.

See C++14 STL Features, Fixes, And Breaking Changes In Visual Studio 14 CTP1

There were also some additional bugs in sleep_until that were fixed in VS 2015 Update 2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM