【问题标题】:What is the default unit of time of c++'s chrono?c++ chrono 的默认时间单位是什么?
【发布时间】:2016-08-28 23:45:53
【问题描述】:

我使用此代码从this answer 测量我的程序的运行时间

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';

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

【问题讨论】:

  • 您可以轻松转换为您想要的任何单位,然后计算这些单位。据我所知,系统时钟使用的单位没有指定,除了它返回的类型。但我在这个问题上并不可靠。
  • 顺便说一句,system_clock 是你不应该在这种情况下使用的那个。

标签: c++ profiling


【解决方案1】:

标准未指定。

20.12.7.1 类 system_clock [time.clock.system]
system_clock 类的对象表示来自系统范围实时时钟的挂钟时间。
类 system_clock {
public:
typedef 见下文 rep;
typedef ratio period;
typedef chrono::duration 持续时间;
typedef chrono::time_point time_point;
static constexpr bool is_steady = unspecified ;
静态时间点 now() noexcept;
// 映射到 C API
static time_t to_time_t(const time_point&t) noexcept;
静态时间点 from_time_t(time_t t) noexcept;
};
typedef unspecified system_clock::rep;

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

【讨论】:

    【解决方案2】:

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

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

    在我的系统上打印:

     1 , 1000000000
    

    即以纳秒为单位的周期(即10-9s)。

    【讨论】:

      猜你喜欢
      • 2012-06-11
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2016-04-02
      • 2022-10-30
      • 2012-02-23
      • 2019-04-04
      • 2015-08-25
      相关资源
      最近更新 更多