std::chrono::high_resolution_clock 的用途是什么?

2021-12-23 00:00:00 time c++ c++11 clock chrono

起初我认为它可以用于性能测量.但说 std::chrono::high_resolution_clock 可能不是稳定(is_steady 可能是 false).也有人说std::chrono::high_resolution_clock 甚至可能是std::chrono::system_clock 的别名,一般不太稳定.所以我不能用这种类型的时钟测量时间间隔,因为随时可能调整时钟,我的测量结果会出错.

At first I thought it can be used for performance measurements. But it is said that std::chrono::high_resolution_clock may be not steady (is_steady may be false). It is also said that std::chrono::high_resolution_clock may even be an alias of std::chrono::system_clock which is generally not steady. So I can't measure time intervals with this type of clock because at any moment the clock may be adjusted and my measurements will be wrong.

同时我无法将 std::chrono::high_resolution_clock 的时间点转换为日历时间,因为它没有 to_time_t 方法.所以我也无法使用这种类型的时钟获得实时.

At the same time I can't convert time points of std::chrono::high_resolution_clock to calendar time because it doesn't have to_time_t method. So I can't get the real time with this type of clock either.

std::chrono::high_resolution_clock有什么用?

推荐答案

没有.

抱歉,我不好.

如果您想使用high_resolution_clock,请选择steady_clock.在 libc++ 和 VS 上,high_resolution_clock 无论如何都是 steady_clock 的类型别名.

If you are tempted to use high_resolution_clock, choose steady_clock instead. On libc++ and VS high_resolution_clock is a type alias of steady_clock anyway.

在 gcc 上 high_resolution_clocksystem_clock 的类型别名,我在这个平台上看到了不止一次 high_resolution_clock::to_time_t 的使用(这是错误的).

On gcc high_resolution_clock is a type alias of system_clock and I've seen more than one use of high_resolution_clock::to_time_t on this platform (which is wrong).

做使用.但是<chrono>的某些部分您应该避免.

Do use <chrono>. But there are parts of <chrono> that you should avoid.

  • 不要使用high_resolution_clock.
  • 避免使用 .count().time_since_epoch() 除非没有其他方法可以完成工作.
  • 避免使用 duration_cast,除非代码没有它就无法编译,并且您希望截断到零的行为.
  • 如果隐式转换编译成功,请避免使用显式转换语法.
  • Don't use high_resolution_clock.
  • Avoid uses of .count() and .time_since_epoch() unless there is no other way to get the job done.
  • Avoid duration_cast unless the code won't compile without it, and you desire truncation-towards-zero behavior.
  • Avoid explicit conversion syntax if an implicit conversion compiles.

相关文章