【问题标题】:asio::high_resolution_timer gives inconsistent results on Windowsasio::high_resolution_timer 在 Windows 上给出不一致的结果
【发布时间】:2021-01-08 21:11:16
【问题描述】:

我正在使用 asio 编写一个用于异步网络和执行的 C++ 应用程序。在我的应用程序中,我希望能够每 50 毫秒异步调用一个函数,并产生大约 1 毫秒的错误。我想出了这个简单的例子来说明我想要做什么。

void timer_callback(asio::high_resolution_timer& timer, const std::error_code& error_code, long long t)
{
    auto current = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
    auto diff = current - t;
    std::cout << diff << '\n';
    timer.expires_at(timer.expiry() + std::chrono::milliseconds(50));
    timer.async_wait([&timer, current](const std::error_code& error_code) { timer_callback(timer, error_code, current); });
}

int main()
{
    asio::io_context io_context;
    asio::high_resolution_timer timer(io_context);
    timer.expires_from_now(std::chrono::milliseconds(50));
    auto current = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count();
    timer.async_wait([&timer, current](const std::error_code& error_code) { timer_callback(timer, error_code, current); });
    io_context.run();
}

我尝试在 Linux 上运行代码并按预期输出程序

50
50
50
50
50
50
50
50
50
50

但是,当我尝试使用 MSVC 编译并在 Windows 上运行程序时,我得到了输出

61
48
45
61
47
48
48
48
47
62

人们会期望 windows 程序也输出与 linux 程序相同的结果,因为我在所有时间中都使用 std::chrono::high_resolution_clock。如果有人可以帮助解释这些差异,我将不胜感激。

【问题讨论】:

    标签: c++ windows timing asio


    【解决方案1】:

    尝试在程序开头附近的某个地方调用timeBeginPeriod(1)。这会将计时器分辨率修改为 ~1ms 而不是 ~15ms。

    您可以在https://randomascii.wordpress.com/2020/10/04/windows-timer-resolution-the-great-rule-change/找到有关计时器分辨率的详细讨论

    【讨论】:

      猜你喜欢
      • 2011-01-07
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 2013-03-12
      相关资源
      最近更新 更多