首页 > 编程语言 >C++获取微妙级时间戳

C++获取微妙级时间戳

时间:2023-05-04 15:24:23浏览次数:34  
标签:std include 获取 auto chrono C++ 微妙 time now

使用C++11提供的std::chrono库

#include <chrono>
#include <ctime>
#include <iomanip>
#include <string>
std::string getTime()
{
    // 获取当前时间点
    auto now = std::chrono::system_clock::now();
    // 将时间长度转换为微秒数
    auto now_us = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
    // 再转成tm格式
    auto now_time_t = std::chrono::system_clock::to_time_t(now);
    auto now_tm = std::localtime(&now_time_t);

    // 可以直接输出到标准输出
    // std::cout << std::put_time(now_tm, "%Y-%m-%d %H:%M:%S.") << std::setfill('0') << std::setw(6) << now_us.count() % 1000000 << std::endl;

    // 格式化字符,年月日时分秒
    std::string now_time_str;
    char buf[32];
    std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", now_tm);
    now_time_str += buf;

    // 格式化微秒
    snprintf(buf, sizeof(buf), ".%06lld", now_us.count() % 1000000);
    now_time_str += buf;

    printf("%s\n", now_time_str.c_str());
    return now_time_str;
}

标签:std,include,获取,auto,chrono,C++,微妙,time,now
From: https://www.cnblogs.com/macrored/p/17371334.html

相关文章