如何实现C++毫秒级时间运算

如何实现C++毫秒级时间运算

在这里插入图片描述

1、概述

本文将介绍如何使用 C++ 标准库中的 <chrono> <ctime> 头文件实现毫秒级时间运算。这两个库都是用于处理时间的库,但功能和用法有所不同。其中,<ctime> 的精度通常只能达到秒级别(对应 10 位 Unix 时间戳),而 <chrono> 最高可以达到纳秒级(对应 13 位时间戳)。


2、目标

我们的目标是实现毫秒级时间加减。例如:

  • 【“14:59:59,900ms”, 加100ms, 要求结果为:“13:00:00,000”】

  • 【“17:00:00,000ms”, 减10ms, 要求结果为:“16:59:59,990”】


2、实现

下面的 C++ 代码展示了如何使用 和 头文件实现毫秒级时间运算:

#include <iostream>
#include <regex>
#include <chrono>
#include <ctime>

int main()
{
    
    
    // 第一步:创建一个标准 ctime 的 timeinfo 结构,表示时间为 2022 年 3 月 2 日 12:34:59
    std::tm tm = {
    
    };
    tm.tm_year = 2022 - 1900; 
    tm.tm_mon = 03 - 1;
    tm.tm_mday = 02;
    tm.tm_hour = 12;
    tm.tm_min = 34;
    tm.tm_sec = 59;
    // 将以上时间换算成10位Unix时间戳:
    auto time_stamp = std::mktime(&tm);
   // 将时间戳转换为 chrono 使用的 13 位时间戳(多出来的 3 位是毫秒信息)
    auto time_point = std::chrono::system_clock::from_time_t(time_stamp);

    // 假设毫秒值是100ms,即2022/03/02 12:34:59,100
    int millisecond = 100;
    // 对毫秒进行加减,实现时间运算(此处我们加上 250ms)
    time_point += std::chrono::milliseconds(millisecond + 250); 

    // 将这个时间戳转换成时间戳字符串
    string chrono_str = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(time_point.time_since_epoch()).count());

    // 使用一个简单的正则表达式区分出前 10 位和后 3 位
    regex pattern(R"(^(\d{10})(\d{3}))");
    smatch matches;
    if (regex_search(chrono_str, matches, pattern))
    {
    
    
        string timestamp_str = matches[1].str();    // 前10 (标准10位时间戳)
        string milliseconds_str = matches[2].str(); // 后3 (毫秒信息)
        
        // 将前10位转换成的tm结构:
        time_t timestamp = std::stoi(timestamp_str);
        std::tm tm_new = *localtime(&timestamp);

        // 将这个10位时间戳改为带格式化输出的字符串
        char time_chr[32];
        // 本例中我们省略了日期信息:
        strftime(time_chr, sizeof(time_chr), "%H:%M:%S", &tm_new);
        result.assign(time_chr);
        result += "," + milliseconds_str; 
        // 最终结果是:12:34:59,350
        cout << result << endl;
    }
    
}

猜你喜欢

转载自blog.csdn.net/rockage/article/details/130189091
今日推荐