簡體   English   中英

C ++計時微秒/納秒不起作用

[英]C++ chrono micro-/nanoseconds not working

編輯:查克·沃爾本的答案解決了我的問題。 工作代碼添加在底部!

我正在嘗試使用chrono lib計算時差(小於millisec。),但是得到的結果非常奇怪/不准確。 另外,如果我嘗試使用小於1毫秒(1000 us / 1000000 ns)的值進行“ sleep_for”操作,則程序將精確睡眠1ms。

我的代碼:

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

在VS 2012和2013中, high_resolution_clock基於系統時間,分辨率為1 ms。 在VS 2015中, high_resolution_clock已正確更新為使用QueryPerformanceCounter因此具有預期的高分辨率。

請參閱Visual Studio 14 CTP1中的C ++ 14 STL功能,修復和重大更改

VS 2015 Update 2中還修復了sleep_until中的一些其他錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM