无法让我的计时数一次以上

Can't get my chrono to count more often than once a ms

本文关键字:一次 我的      更新时间:2023-10-16

我试图让我的代码测量时间持续时间短于1ms,但只是不能。

我已经搜索了,但还没有设法理解如何做到这一点。我添加了一些我认为相关的代码。

template <class Clock>
void
display_precision()
{
    typedef std::chrono::duration<double, std::nano> NS;
    NS ns = typename Clock::duration(1);
    std::cout << ns.count() << " nsn";
}

int main()
{

    display_precision<std::chrono::high_resolution_clock>();
    display_precision<std::chrono::system_clock>();
    display_precision<std::chrono::steady_clock>();
    std::cout << std::chrono::high_resolution_clock::period::num 
        << "/" << std::chrono::high_resolution_clock::period::den;

    std::chrono::high_resolution_clock::time_point nowTime;
    std::chrono::high_resolution_clock::time_point startTime;
    startTime = std::chrono::high_resolution_clock::now();
    int count = 0;
    do
    {
        nowTime = std::chrono::high_resolution_clock::now();
        std::chrono::high_resolution_clock::duration diff = nowTime - startTime;
        __int64 difference = std::chrono::duration_cast<std::chrono::microseconds>(diff).count();
        printf("n%i", difference);
        count++;
        if (std::chrono::duration_cast<std::chrono::seconds>(diff).count() > 2) { break; }
    } while (1);
}

我得到的输出是这样的:

100 ns
100 ns
100 ns
1 / 10000000

:

2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2996299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2997299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2998299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
2999299
3000300

正如你所看到的,difference每毫秒改变一次,并在其间保持不变,尽管它在此期间循环了15次左右(尽管我据说有100ns的精度)。

此外,这似乎不是一个printf瓶颈,因为我试着用数据加载一个向量,我得到了相同的结果。

[Windows 7 Professional, VS Community 2013]

这是VS2013的问题,在VS2015中修复。来自:Visual Studio 2015 RTM details

"时间类型high_resolution_clock和steady_clock已被修复。c++ 11 "