asio::高分辨率计时器在Windows上给出不一致的结果 我正在使用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(); }

asio::高分辨率计时器在Windows上给出不一致的结果 我正在使用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(); },c++,windows,timing,asio,C++,Windows,Timing,Asio,然而,当我尝试用MSVC编译并在windows上运行程序时,我得到了输出 61 48 45 61 47 48 48 48 47 62 由于我在所有计时中都使用std::chrono::high_resolution_clock,人们可能会期望windows程序也能输出与linux程序相同的结果。如果有人能帮助解释这些差异,我将不胜感激。试着在程序开始时的某个地方调用timeBeginPeriod(1)。这将计时器分辨率修改为~1ms,而不是~15ms 有关计时器分辨率的详细讨论,请访问 61

然而,当我尝试用MSVC编译并在windows上运行程序时,我得到了输出

61
48
45
61
47
48
48
48
47
62

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

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

有关计时器分辨率的详细讨论,请访问

61
48
45
61
47
48
48
48
47
62