C++获取微妙级时间戳

发布时间 2023-05-04 15:19:30作者: Macrored

使用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::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;
}