steady_clock在windows/cygwin上只有10ms分辨率吗?

问题描述 投票:0回答:2

我有一个令人惊讶的观察结果,即在测量持续时间时,steady_clock 的分辨率只有 10 毫秒。我在 cygwin 下为 windows 编译。这是可悲的事实还是我做错了什么?

auto start = std::chrono::steady_clock::now();
/*...*/
auto end = std::chrono::steady_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>
                                                   (end - start).count();

结果为 10000,20000 等

c++ windows c++11 cygwin
2个回答
1
投票

std::steady_clock
的分辨率取决于实现,您不应依赖于精确的最短持续时间。它因平台/编译器实现而异。

来自 http://cppreference.com:

类 std::chrono::steady_clock 表示单调时钟。时间 该时钟的点数不能随着物理时间的前进而减少。 该时钟与挂钟时间无关,最适合 测量间隔。

相关:std::system_clock 和 std::steady_clock 之间的区别?

如果您不关心单调性(即,您不关心程序运行时是否有人更改挂钟),那么您可能最好使用 std::高分辨率时钟。 (后者仍然取决于实现)


0
投票

在Windows中,steady_clock和high_resolution_clock具有相同的time_stamp和duration类型。 stable_clock 依赖于 GetSystemTimeAsFileTime(),其分辨率为 100ns。 GetSystemTimeAsFileTime() 内部布局可与 x86-CPU 上的 RDTSC 配合使用。通过以下程序,您可以检查 high_resolution_clock 和 stable_clock 的最短可测量距离。

#include <iostream>
#include <chrono>

using namespace std;
using namespace chrono;

int main()
{
    
    auto check = []<typename Clock>()
    {
        using time_t = Clock::time_point;
        using dur_t = Clock::duration;
        auto ticks = [] { return Clock::now(); };
        time_t tLast = ticks();
        dur_t dMin = dur_t::max();
        for( size_t r = 5; r--; )
        {
            time_t tNext;
            while( (tNext = ticks()) == tLast );
            dur_t dDiff = tNext - tLast;
            dMin = dMin < dDiff ? dMin : dDiff;
            tLast = tNext;
        }
        cout << duration_cast<nanoseconds>( dMin ).count() << endl;
    };
    check.template operator()<steady_clock>();
    check.template operator()<high_resolution_clock>();
}

对于 Windows,这会打印

100
两次。对于 Linux/x86,这取决于任一时钟的 ::now() 执行速度。使用我的 AMD Zen4 CPU 和 WSL2,两个时钟的时间都是 10ns。

© www.soinside.com 2019 - 2024. All rights reserved.