C ++ chrono微/纳秒无法正常工作

时间:2016-06-21 15:45:33

标签: c++ visual-studio-2013 windows-7 chrono

  

编辑:Chuck Walbourn的回答解决了我的问题。工作代码添加在底部!

我正在尝试使用chrono lib计算时差(小于millisec。)但是我得到了非常奇怪/不准确的结果。如果我尝试" sleep_for"如果值小于1 ms(1000 us / 1000000 ns),程序将完全休眠1 ms。

我的代码:

#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;
    }
}

我的输出:

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. . .

它显然只在1毫秒内递增,但这仍然无法解释有时添加的随机hunderd。有人可以帮助我:(

我正在运行Visual Studio 2013和Windows 7

添加了工作代码:

#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;
    }
}

1 个答案:

答案 0 :(得分:0)

在VS 2012和2013中,public interface ISportello extends Remote{ public boolean serviRichiesta(int id) throws RemoteException; } 基于系统时间,分辨率为1毫秒。在VS 2015中,high_resolution_clock已正确更新以使用high_resolution_clock,因此它具有预期的高分辨率。

请参阅C++14 STL Features, Fixes, And Breaking Changes In Visual Studio 14 CTP1

QueryPerformanceCounter中还有一些其他错误已修复VS 2015 Update 2