【问题标题】:C++ chrono micro-/nanoseconds not workingC ++ chrono微/纳秒不起作用
【发布时间】:2016-10-23 06:27:58
【问题描述】:

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

我正在尝试使用 chrono lib 计算时间差(小于毫秒),但得到的结果非常奇怪/不准确。此外,如果我尝试使用小于 1 ms (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 毫秒内增加,但这仍然不能解释有时添加的随机百分率。有人可以帮我吗:(

我正在运行 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;
    }
}

【问题讨论】:

  • 您提供的代码没有sleep?还要记住,检查时间需要时间。
  • 请注意,VS2013 中的high_resolution_clock 在其实现中没有使用特别高分辨率的计时器。在 VS2015 中,我相信他们已经修复它以使用 QueryPerformanceCounter API。 connect.microsoft.com/VisualStudio/feedback/details/1112449/…
  • 仅供参考:sleep_for 阻止当前线程的执行至少指定的 sleep_duration,因此它不能做出非常强的保证。
  • 这是一种将QueryPerformanceCounter 变成计时时钟的方法:stackoverflow.com/a/15755865/576911

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


【解决方案1】:

在 VS 2012 和 2013 中,high_resolution_clock 基于系统时间,分辨率为 1 毫秒。在 VS 2015 中,high_resolution_clock 已正确更新为使用 QueryPerformanceCounter,因此它具有预期的高分辨率。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-05
    • 2017-10-29
    • 2017-11-06
    相关资源
    最近更新 更多