【发布时间】: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。如果有人可以帮助解释这些差异,我将不胜感激。
【问题讨论】: