C++11 clock

一 简介
  1. C++11 在chrono库中提供了三种时钟 clock: system_clock,steady_clock 和 high_resolution_clock。
  2. 头文件 < chrono >。
二 system_clock
  1. system_clock 来自系统范围实时时钟的壁钟时间(wall clock)。

  2. system_clock是唯一有能力映射其时间点到 C 风格时间的 C++ 时钟。

    It is the only C++ clock that has the ability to map its time points to C-style time.

  3. system_clock可以不单调:大多数系统上,系统时间可以在任何时候被调节。

    It may not be monotonic: on most systems, the system time can be adjusted at any moment.
    The system_clock’s time value can be internally adjusted at any time by the operating system.

  4. 例子

    // 是否为稳定时钟
    cout << "system_clock::is_steady: " << std::boolalpha << system_clock::is_steady << endl;
    {
      auto start = system_clock::now();
    
      int i = 0;
      while (i < 10000)
        i++;
    
      duration<double> time = system_clock::now() - start;
      cout << "time: " << time.count() << endl;
    }
    {
      auto t = system_clock::to_time_t(system_clock::now());  // to_time_t
      cout << asctime(gmtime(&t)) << endl;
      cout << asctime(localtime(&t)) << endl;
    
      duration<double> time =
          system_clock::now() - system_clock::from_time_t(t); // from_time_t
      cout << "time: " << time.count() << endl;
    }
    
  • 输出

    system_clock::is_steady: false
    time: 1.61e-05
    Tue Sep 29 03:55:00 2020
    Tue Sep 29 11:55:00 2020
    time: 0.506771
    
三 steady_clock
  1. steady_clock是单调时钟。

    Class std::chrono::steady_clock represents a monotonic clock.

  2. 常用于耗时计算 。(stopwatch)

  3. 例子

    cout << "steady_clock::is_steady: " << std::boolalpha << steady_clock::is_steady << endl;
    {
      auto start = steady_clock::now();
    
      int i = 0;
      while (i < 10000)
        i++;
    
      duration<double> time = steady_clock::now() - start;
      cout << "time: " << time.count() << endl;
    }
    
  • 输出

    steady_clock::is_steady: true
    time: 1.6078e-05
    
四 high_resolution_clock
  1. high_resolution_clock是当前系统能够提供的最高精度的时钟。

  2. high_resolution_clock在不同标准库实现之间实现不一致,应该避免使用它。通常它只是 std::chrono::steady_clock 或 std::chrono::system_clock 的别名,但实际是哪个取决于库或配置。

    It may be an alias of std::chrono::system_clock or std::chrono::steady_clock, or a third, independent clock.

  3. 例子

    cout << "high_resolution_clock::is_steady: " << std::boolalpha
         << high_resolution_clock::is_steady << endl;
    {
      auto start = high_resolution_clock::now();
    
      int i = 0;
      while (i < 10000)
        i++;
    
      duration<double> time = high_resolution_clock::now() - start;
      cout << "time: " << time.count() << endl;
    }
    
  • 输出

    high_resolution_clock::is_steady: true
    time: 1.6077e-05
    
五 参考
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值