下面是具体的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 auto& getCurrentTimeStr(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; }
系统当前共有 426 篇文章