c++和ubuntu系统如何获取当前系统的纳秒数和时间字符串
作者:yunjinqi    类别:编程    日期:2025-04-24 16:30:07    阅读:59 次    消耗积分:0 分    

下面是具体的time_utils.h的代码,可以获取纳秒数和包含纳秒的时间字符串

#pragma once

#include <string>
#include <chrono>
#include <ctime>

namespace Common {
typedef int64_t Nanos;

  /**
   * 纳秒与微秒的换算关系
   */
constexpr Nanos NANOS_TO_MICROS = 1000;
  /**
   * 微秒与毫秒的换算关系
   */
constexpr Nanos MICROS_TO_MILLIS = 1000;
  /**
   * 毫秒与秒的换算关系
   */
constexpr Nanos MILLIS_TO_SECS = 1000;
  /**
   * 纳秒与毫秒的换算关系
   */
constexpr Nanos NANOS_TO_MILLIS = NANOS_TO_MICROS * MICROS_TO_MILLIS;
  /**
   * 纳秒与秒的换算关系
   */
constexpr Nanos NANOS_TO_SECS = NANOS_TO_MILLIS * MILLIS_TO_SECS;

  /**
   * 获取当前时间的纳秒数
   * 返回从系统纪元(1970年1月1日)开始到现在的纳秒数
   * 使用系统的高分辨率时钟,提供纳秒级分辨率
   * 
   * @return 当前时间的纳秒数值(自纪元开始)
   */
inline auto getCurrentNanos() noexcept {
    // 获取当前时间点,转换为纪元以来的时间间隔,并转换为纳秒数
return std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}

  /**
   * 获取格式化的当前时间字符串
   * 将当前时间格式化为易读的字符串:"YYYY-MM-DD HH:MM:SS.nanoseconds"
   * 例如:"2023-05-15 14:30:22.123456789"
   * 
   * @param time_str 用于存放格式化结果的字符串指针
   * @return 格式化后的时间字符串的引用
   */
inline autogetCurrentTimeStr(std::string* time_str) {
    // 获取当前系统时间点
const auto now = std::chrono::system_clock::now();
const auto now_as_time = std::chrono::system_clock::to_time_t(now);
    // 创建tm结构体存储分解后的时间
struct tm now_tm;
    // 将time_t类型转换为本地时间并存入tm结构体
    // localtime_r是线程安全版本
localtime_r(&now_as_time, &now_tm);

    // 计算纳秒部分,取模确保只有纳秒部分
const auto now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>
(now.time_since_epoch()).count() % 1000000000;

    // 使用snprintf格式化时间字符串
char buff[128];
snprintf(buff, sizeof(buff), "%04d-%02d-%02d %02d:%02d:%02d.%09ld",
1900 + now_tm.tm_year,  // 年份需要加1900
now_tm.tm_mon + 1,      // 月份从0开始,需要加1
now_tm.tm_mday,         // 日
now_tm.tm_hour,         // 小时
now_tm.tm_min,          // 分钟
now_tm.tm_sec,          // 秒
now_ns);                // 纳秒

    // 将格式化的字符串赋值给传入的字符串指针
time_str->assign(buff);
    // 返回结果字符串的引用
return *time_str;
}
}


例子:

#include <iostream>
#include "time_utils.h"

int main() {
std::string time_str;
std::cout << "Current time: " << Common::getCurrentTimeStr(&time_str) << std::endl;
std::cout << "Current nanoseconds: " << Common::getCurrentNanos() << std::endl;
return 0;
}


版权所有,转载本站文章请注明出处:云子量化, https://www.yunjinqi.top/article/486
上一篇:如何过好这一生25、如何才能活在当下
下一篇:ubuntu上使用c++绑核进行启动多线程代码及例子

系统当前共有 466 篇文章