You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ std::chrono::high_resolution_clock time_since_epoch返回值过小,如何正确获取1970年以来的微秒时间

问题原因

C++标准未强制规定std::chrono::high_resolution_clock的纪元起点,不同平台的实现存在本质差异:

  • Windows平台的high_resolution_clock默认以系统开机时间作为纪元,你拿到的269104616249实际是开机至今的微秒数,换算后约为3天,和你观测到的数值过小的现象完全吻合
  • 部分类Unix平台虽然会用1970年1月1日作为high_resolution_clock的纪元,但这属于平台自定义特性,没有跨平台通用性

解决方案

如果需要稳定获取Unix纪元(1970年1月1日)至今的微秒时间戳,优先使用std::chrono::system_clock,C++标准明确规定system_clock的纪元为Unix时间,所有平台实现一致。

修正后代码示例:

#include <chrono>
#include <type_traits>

using namespace std::chrono;

int64_t NowInMicroseconds() {
    auto epoch_duration = system_clock::now().time_since_epoch();
    static_assert(std::is_same<decltype(duration_cast<microseconds>(epoch_duration).count()), int64_t>::value);
    return duration_cast<microseconds>(epoch_duration).count();
}

int64_t result = NowInMicroseconds();

补充说明

  • 低于C++20的标准环境中,主流平台的system_clock精度普遍可以达到微秒级,完全满足常规使用需求
  • 如果你对精度有极端要求,可以结合平台原生API实现:Windows下用GetSystemTimePreciseAsFileTime、Linux下用clock_gettime(CLOCK_REALTIME, ...),可以同时保证精度和纪元正确性

内容的提问来源于stack exchange,提问作者Semyon Tikhonenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 02:09:04