c++ 计时的默认时间单位是什么?

What is the default unit of time of c++'s chrono?

本文关键字:单位 是什么 时间 默认 c++      更新时间:2023-10-16

我使用这段代码根据这个答案来测量程序的运行时间

auto start = std::chrono::system_clock::now();
/* do some work */
auto end = std::chrono::system_clock::now();
auto elapsed = end - start;
std::cout << elapsed.count() << 'n';

我只需要测量运行时间来寻找趋势,但我有点好奇那是什么单位

您可以轻松地自己检查,使用以下代码:

using Clock = std::chrono::system_clock;
using Duration = Clock::duration;
std::cout << Duration::period::num << " , " << Duration::period::den << 'n';

在我的系统上它打印:

 1 , 1000000000

即以纳秒为单位的周期(即10&减去;9s)。

标准未指定

20.12.7.1 Class system_clock [time.clock.system]
system_clock类的对象表示来自全系统实时时钟的挂钟时间。
类system_clock {
公众:

typedef ratio<</strong>;
typedef空间:duration<</strong>;
time_point;
静态constexpr bool is_steady =未指定;
静态time_point now() noexcept;
//映射到C API
静态time_t to_time_t (const time_point&t) noexcept;
静态time_point from_time_t(time_t) noexcept;

}; typepedef unspecified system_clock::rep;

就我个人而言,我认为将结果显式地转换为您想要的特定duration总是一个好主意。