【发布时间】:2020-12-09 14:08:14
【问题描述】:
我想通过网络连接发送一个时间点来检测 ping 时间并进行其他计算。时间必须具有毫秒精度,但使用:
auto currently = std::chrono::time_point_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now()
);
...返回(当然)系统时间,当然不是UTC。有什么方法可以计算 UTC 值而不将 time_point 转换为 time_t 然后再返回?我读过一些关于 std::chrono::utc_clock 的内容,但即使使用 C++20 我也无法在 <chrono> 标头中找到定义。
编辑
这将是一个可行的解决方案,但它是一个糟糕的解决方案,因为它非常低效......必须有更好的东西:
auto currently = std::chrono::time_point_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now()
);
time_t time = std::chrono::system_clock::to_time_t(currently);
struct tm *tm = gmtime(&time);
// Create a new time_point from struct tm that is in UTC now
【问题讨论】:
-
::std::chrono::utc_clock原则上存在,但看起来 clang 和 GCC 都没有它在他们的标准库中。这对于最新的语言标准来说很常见。并非所有功能都被所有编译器实现。 -
system_clock返回一个std::chrono::time_point,它通常相对于 Unix 纪元,但在 C++20 (source) 之前不能保证。所以它与时区完全无关,在 C++20 中它会适合你的目的。 -
反正要检测ping时间,这种办法恐怕没用!不同系统的时钟很少同步到毫秒。典型的方法是测量往返时间:发送 ping,等待对等方以 pong 响应。当您收到乒乓球时,计算经过的时间并除以 2。
-
目前不知道如何实现ping计算。但基本上我想通过 TCP 发送消息,每条消息都应该有一个时间戳,因为它们应该用相应的时间点记录。
-
@Thomas:现在的 NTP 让你相当接近。