C++中的时间相关处理

time.h

在C++11之前,C++ 程序员通常使用 C 语言标准库中的时间和日期函数来处理时间,这些函数的精度通常只有秒级别。这些传统的 C 语言 API 包括 time.h 头文件中定义的函数,如 time(), gmtime(), localtime(), mktime() 等。这些函数使用 time_t 类型来表示时间,并且与 struct tm 结构体一起使用来处理日期和时间。

#include <iostream>
#include <ctime>

int main() {
    // 获取当前时间
    time_t now = time(nullptr);

    // 将 time_t 类型的时间转换为 tm 结构体,以便于读取和格式化
    tm* local_time = localtime(&now);

    // 打印当前时间的各个部分
    std::cout << "Current year: " << 1900 + local_time->tm_year << std::endl;
    std::cout << "Current month: " << 1 + local_time->tm_mon << std::endl;
    std::cout << "Current day: " << local_time->tm_mday << std::endl;
    std::cout << "Current hour: " << local_time->tm_hour << std::endl;
    std::cout << "Current minute: " << local_time->tm_min << std::endl;
    std::cout << "Current second: " << local_time->tm_sec << std::endl;

    // 使用 asctime() 将 tm 结构体转换为可读的字符串形式
    std::cout << "Current time: " << asctime(local_time);

    // 使用 mktime() 来将 tm 结构体转换为 time_t 类型的时间戳
    time_t time_from_tm = mktime(local_time);

    // 再次打印转换后的时间戳
    std::cout << "Time from tm struct: " << ctime(&time_from_tm);

    // 使用 difftime() 计算两个时间的差(秒)
    time_t future_time = now + 3600; // Add one hour to the current time
    double time_difference = difftime(future_time, now);
    std::cout << "Time difference: " << time_difference << " seconds" << std::endl;

    return 0;
}

由于这些传统方法在处理时间和日期时存在局限性,例如精度不足以及跨平台兼容性问题,C++11 引入了 std::chrono 库,它提供了更高精度的时间间隔和时钟,以及时间点的表示,从而极大地改进了 C++ 中的时间处理能力。

C++11中的引入的时间处理部分:chrono

主要组件

  • 时钟(Clocks):std::chrono提供了不同类型的时钟,主要有以下几种:

    • std::chrono::system_clock:基于系统时间的时钟,可能会受到系统时间变化的影响。
    • std::chrono::steady_clock:提供一个稳定的时间来源,不受系统时间调整的影响。
    • std::chrono::high_resolution_clock:通常提供最高的时间分辨率。
  • 时间间隔(Duration):std::chrono::duration类模板用于表示两个时间点之间的时间长度。它非常灵活,允许用户指定时间单位,如秒、毫秒、微秒等。

  • 时间点(Time Points):std::chrono::time_point类模板表示特定的时间点。结合时钟和持续时间,它可以表示从纪元(通常是1970年1月1日午夜)开始的某个具体时间。

使用场景

  • 性能测量:通过计算两个时间点之间的差异,可以测量代码块的执行时间。
  • 定时任务:可以创建定时任务,比如使用std::this_thread::sleep_for让线程暂停执行一段时间。
  • 时间格式化:可以将时间点格式化为易读的字符串形式。

demo代码

性能测量:

#include <iostream>
#include <chrono>
#include <thread>

void func1(int matrix[1000][1000]){
    for(auto i=0;i<1000;i++){
        for(auto j=0;j<1000;j++){
            matrix[i][j] += 1;
        }
    }
}

void func2(int matrix[1000][1000]){
    for(auto i=0;i<1000;i++){
        for(auto j=0;j<1000;j++){
            matrix[j][i] += 1;
        }
    }
}

int main(){
    int matrix[1000][1000] = {0};
    auto start = std::chrono::steady_clock::now();
    func1(matrix);
    auto end = std::chrono::steady_clock::now();

    auto dt = end-start;
    int64_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(dt).count();

    std::cout << "func1 run time:" << duration << std::endl;
    start = std::chrono::steady_clock::now();
    func2(matrix);
    end = std::chrono::steady_clock::now();

    dt = end-start;
    duration = std::chrono::duration_cast<std::chrono::milliseconds>(dt).count();

    std::cout << "func2 run time:" << duration << std::endl;
    return 0;
} 

定时任务:

#include <iostream>
#include <chrono>
#include <thread>

int main() {
    // 获取当前时间点
    auto now = std::chrono::system_clock::now();

    // 休眠1秒
    std::this_thread::sleep_for(std::chrono::seconds(1));

    // 再次获取当前时间点
    auto later = std::chrono::system_clock::now();

    // 计算时间差
    auto duration = later - now;
    int64_t sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
    std::cout << "Time taken: " << sec << " seconds\n";

    return 0;
}

打印现在时间:

#include <iostream>
#include <chrono>
#include <iomanip>

int main() {
    // 获取当前时间点
    auto now = std::chrono::system_clock::now();
    
    // 转换为time_t类型,这在C++11中是time_t的高精度版本
    std::time_t now_time_t = std::chrono::system_clock::to_time_t(now);
    
    // 将time_t类型转换为tm结构体,以便于读取和格式化
    std::tm now_tm;
    localtime_s(&now_tm, &now_time_t); // 使用localtime_s是安全的,因为localtime_r在某些平台上不可用

    // 打印当前时间的各个部分
    std::cout << "Current year: " << 1900 + now_tm.tm_year << std::endl;
    std::cout << "Current month: " << 1 + now_tm.tm_mon << std::endl;
    std::cout << "Current day: " << now_tm.tm_mday << std::endl;
    std::cout << "Current hour: " << now_tm.tm_hour << std::endl;
    std::cout << "Current minute: " << now_tm.tm_min << std::endl;
    std::cout << "Current second: " << now_tm.tm_sec << std::endl;

    // 使用chrono的duration来计算一个小时后的时间
    auto one_hour_later = now + std::chrono::hours(1);

    // 计算时间差(以秒为单位)
    auto time_difference = std::chrono::duration_cast<std::chrono::seconds>(one_hour_later - now);

    // 格式化当前时间和时间差输出
    std::cout << "Current time: " << std::put_time(&now_tm, "%Y-%m-%d %H:%M:%S") << std::endl;
    std::cout << "Time difference: " << time_difference.count() << " seconds" << std::endl;

    return 0;
}

相关推荐

  1. C++时间相关处理

    2024-04-29 12:48:02       14 阅读
  2. MySQL对日期时间处理

    2024-04-29 12:48:02       40 阅读
  3. [AIGC] Flink时间语义:精确处理数据

    2024-04-29 12:48:02       24 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-29 12:48:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-29 12:48:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-29 12:48:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-29 12:48:02       18 阅读

热门阅读

  1. python基础知识

    2024-04-29 12:48:02       12 阅读
  2. Unity坐标相关——坐标系,单位

    2024-04-29 12:48:02       13 阅读
  3. Node.js 的 fs 模块分析及其应用

    2024-04-29 12:48:02       16 阅读
  4. 使用动态ip上网稳定吗?

    2024-04-29 12:48:02       13 阅读
  5. 安装k8s

    2024-04-29 12:48:02       12 阅读
  6. web server apache tomcat11-20-connectors 连接器

    2024-04-29 12:48:02       14 阅读
  7. Odoo用浏览器与企业版客户端的区别

    2024-04-29 12:48:02       12 阅读
  8. ssh连接自动断开的几种可能

    2024-04-29 12:48:02       17 阅读
  9. linux 提权总结_linux提权

    2024-04-29 12:48:02       14 阅读
  10. 阿赵Json工具AzhaoJson的Lua版本

    2024-04-29 12:48:02       11 阅读
  11. 【Spark】读取本地文件

    2024-04-29 12:48:02       9 阅读
  12. rust语言tokio库spawn, blocking_spawn等的使用

    2024-04-29 12:48:02       20 阅读
  13. Element

    Element

    2024-04-29 12:48:02      14 阅读
  14. H3C 交换机配置 IGMP-snooping 注意点

    2024-04-29 12:48:02       12 阅读