如何在 C++ 中以毫秒为单位获取当前时间? [英] How can I get current time of day in milliseconds in C++?

查看:68
本文介绍了如何在 C++ 中以毫秒为单位获取当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是,我必须以某种方便的格式以毫秒为单位获取当前时间.

The thing is, I have to somehow get current time of day in milliseconds in convenient format.

所需输出的示例:

21 小时 04 分 12 秒 512 毫秒

21 h 04 min 12 s 512 ms

我知道如何在几秒钟内获得这种格式,但我不知道如何以毫秒为单位?

I know how to get this format in seconds, but I have no idea how to get my hands on milliseconds?

推荐答案

使用便携式 std::chrono

auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) -
          std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());

std::cout << std::put_time(std::localtime(&time), "%H h %M m %S s ");
std::cout << ms.count() << " ms" << std::endl;

输出:

21 小时 24 米 22 秒 428 毫秒

21 h 24 m 22 s 428 ms

实例

正如@user4581301,在某些系统上std::system_clock 可能没有足够的分辨率来以毫秒为单位准确表示当前时间.如果是这种情况,请尝试使用 std::high_resolution_clock 用于计算自上一秒以来的毫秒数.这将确保您的实施提供最高的可用分辨率.

As pointed out by @user4581301, on some systems std::system_clock might not have enough resolution for accurately representing current time in milliseconds. If that is the case, try using std::high_resolution_clock for calculating the number of milliseconds since the last second. This will ensure the highest available resolution provided by your implementation.

从两个时钟中获取时间将不可避免地导致您获得两个不同的时间点(无论时差有多小).所以请记住,使用单独的时钟来计算毫秒不会在秒和毫秒周期之间产生完美的同步.

Taking the time from two clocks will inevitably lead you to get two separate points in time (however small the time difference will be). So keep in mind that using a separate clock for calculating the milliseconds will not yield perfect synchronization between the second, and millisecond periods.

// Use system clock for time.
auto now = std::chrono::system_clock::now();

/* A small amount of time passes between storing the time points. */

// Use separate high resolution clock for calculating milliseconds.
auto hnow = std::chrono::high_resolution_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(hnow.time_since_epoch()) -
          std::chrono::duration_cast<std::chrono::seconds>(hnow.time_since_epoch());

此外,似乎无法保证 std::high_resolution_clockstd::system_clock 的滴答事件是同步的,因此毫秒周期可能与系统时钟给定的当前秒的周期性更新不同步.

Also, there seems to be no guarantee that the tick events of std::high_resolution_clock and std::system_clock are synchronized, and because of this the millisecond period might not be in sync with the periodic update of the current second given by the system clock.

由于这些原因,当 <1 秒精度很重要时,不应使用单独的高分辨率时钟作为毫秒分辨率.

Because of these reasons, using a separate high resolution clock for millisecond resolution should not be used when <1 second precision is critical.

这篇关于如何在 C++ 中以毫秒为单位获取当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆