#include<chrono>

  • 阿里云国际版折扣https://www.yundadi.com

  • 阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

    #include <chrono> 是C++标准库中用于处理时间和持续时间的头文件。chrono库提供了一系列用于表示时间点、时间段和时钟的类和函数。以下是chrono库中一些常用接口和用法

    1. 持续时间Durations

    std::chrono::duration 是用于表示时间间隔的类模板。你可以用不同的时间单位来表示持续时间例如秒std::chrono::seconds、毫秒std::chrono::milliseconds、微秒std::chrono::microseconds和纳秒std::chrono::nanoseconds等。

    常用用法

    • 创建持续时间std::chrono::seconds sec(5);auto sec = std::chrono::seconds(5);
    • 获取持续时间的数值int64_t count = sec.count();
    1. 时间点Time Points

    std::chrono::time_point 是用于表示时间点的类模板。通常时间点是相对于某个时钟Clock的。chrono库提供了以下三种时钟

    • std::chrono::system_clock系统时钟它表示真实世界中的时间。
    • std::chrono::steady_clock稳定时钟它保证从程序开始运行到结束时间只会向前不会发生调整。
    • std::chrono::high_resolution_clock高分辨率时钟它提供了最高精度的计时。

    常用用法

    • 获取当前时间点auto now = std::chrono::system_clock::now();
    • 时间点转换为时间戳std::time_t timestamp = std::chrono::system_clock::to_time_t(now);
    1. 计算持续时间

    你可以对持续时间执行加法、减法和乘法等操作。例如

    auto duration1 = std::chrono::seconds(5);
    auto duration2 = std::chrono::milliseconds(500);
    auto sum = duration1 + duration2;
    
    1. 测量代码执行时间

    chrono库常用于测量代码段的执行时间。以下是一个示例

    #include <iostream>
    #include <chrono>
    #include <thread>
    
    int main() {
        // 记录开始时间点
        auto start = std::chrono::high_resolution_clock::now();
    
        // 要测量的代码段
        std::this_thread::sleep_for(std::chrono::seconds(1));
    
        // 记录结束时间点
        auto end = std::chrono::high_resolution_clock::now();
    
        // 计算持续时间
        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
    
        // 输出结果
        std::cout << "Elapsed time: " << duration << " milliseconds" << std::endl;
    
        return 0;
    }
    

    在这个示例中我们使用std::chrono::high_resolution_clock来测量代码执行时间并将结果转换为毫秒。

  • 阿里云国际版折扣https://www.yundadi.com

  • 阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6