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

时间:2016-08-28 23:45:54

标签: c++ profiling

我使用此代码从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';

我只需要测量运行时间来寻找趋势,但我对那个单位感到好奇。

2 个答案:

答案 0 :(得分:2)

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

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

在我的系统上打印:

 1 , 1000000000

纳秒的句号(即10 -9 s)。

答案 1 :(得分:1)

标准未指明。

  

20.12.7.1类system_clock [time.clock.system]
  system_clock类的对象表示系统范围实时时钟的挂钟时间   class system_clock {
  市民:
   typedef见下面的代表;
   typedef ratio&lt;未指明,未指明&gt;期;
   typedef chrono :: duration&lt; rep,period&gt;持续时间;
  typedef chrono :: time_point time_point;
  static constexpr bool is_steady = unspecified;
  static time_point now()noexcept;
  //映射到C API
  static time_t to_time_t(const time_point&amp; t)noexcept;
  static time_point from_time_t(time_t t)noexcept;
  };
   typedef未指定的system_clock :: rep ;

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