如何实现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;
    }
    
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rockage

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值