不能直接用clock()或time(),因clock()返回CPU时间且Windows下分辨率常为15ms,time()仅精确到秒;跨平台毫秒级时间戳应使用GetTickCount64()(Windows)或clock_gettime(CLOCK_MONOTONIC)(POSIX),辅以gettimeofday()兜底。

为什么不能直接用 clock() 或 time()
这两个函数在不同平台下精度和语义差异很大:clock() 返回的是 CPU 时间(不是 wall-clock),且在 Windows 下分辨率常为 15ms;time() 只精确到秒。跨平台获取毫秒级时间戳,必须绕过这些陷阱。
核心思路是:Windows 用 GetTickCount64()(可靠、无 wrap-around 风险),POSIX 系统用 clock_gettime(CLOCK_MONOTONIC, ...)(推荐)或退化到 gettimeofday()(仅当 clock_gettime 不可用时)。
-
GetTickCount64()在 Windows Vista+ 全面可用,返回自系统启动起的毫秒数,64 位整数,永不回绕 -
clock_gettime(CLOCK_MONOTONIC, ...)是 Linux/macOS 标准,精度高、单调、不随系统时间调整而跳变 - 避免用
CLOCK_REALTIME—— 它受 NTP 调整、手动改系统时间影响,不适合计时差
如何写一个可编译通过的跨平台头文件
把平台判断逻辑收进头文件,不依赖外部构建配置(比如不用 CMake 的 add_compile_definitions 做宏开关),直接用预定义宏判断:
#ifdef _WIN32
#include <windows.h>
#else
#include <time.h>
#include <sys/time.h>
#endif
<p>inline uint64_t GetTimeMs() {</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/6e7abc4abb9f" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">C++免费学习笔记(深入)</a>”;</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/gongju/2823" title="C++14"><img
src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/gongju/2823" title="C++14">C++14</a>
<p>C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p>
</div>
<a href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><h1>ifdef _WIN32</h1><pre class='brush:php;toolbar:false;'>return GetTickCount64();else
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
return static_cast<uint64_t>(ts.tv_sec) * 1000 + ts.tv_nsec / 1000000;
} else {
// fallback: gettimeofday (microsecond precision, but widely available)
struct timeval tv;
gettimeofday(&tv, nullptr);
return static_cast<uint64_t>(tv.tv_sec) * 1000 + tv.tv_usec / 1000;
}endif
}
注意:GetTickCount64() 在 MinGW-w64 和 MSVC 下都可用;clock_gettime() 在 macOS 10.12+ 和主流 Linux 发行版默认可用 —— 如果目标环境老旧(如 CentOS 6),fallback 到 gettimeofday() 是必要兜底。
常见链接错误和编译警告怎么修
Linux 下如果出现 undefined reference to `clock_gettime',不是代码错,是链接器没加 -rt(即 librt)。GCC/Clang 默认不自动链接该库。
- 编译命令要显式加上
-lrt(放在源文件之后,如:g++ main.cpp -lrt) - CMake 中需写:
target_link_libraries(your_target rt) - macOS 不需要
-lrt,但要注意CLOCK_MONOTONIC在较老版本可能未定义 —— 可加#ifndef CLOCK_MONOTONIC宏保护 - Clang++ 在某些配置下对
gettimeofday()报deprecated警告,忽略即可,它仍是 POSIX 标准且稳定
精度和单调性真的够用吗?
这个 GetTimeMs() 满足绝大多数场景:游戏帧计时、网络超时、性能采样。但它不是纳秒级高精度计时器,也不适合做严格实时调度。
- Windows
GetTickCount64()实际底层基于 HPET 或 TSC,但 Windows 内核会做平滑处理,通常误差在 ±1–2ms - Linux
clock_gettime(CLOCK_MONOTONIC)在现代硬件上可达微秒级,但除以 1e6 得到毫秒后,已抹平大部分波动 - 两次调用之间若发生系统休眠,
CLOCK_MONOTONIC和GetTickCount64()都会暂停计数 —— 这是设计使然,不是 bug - 如果业务要求“真实流逝时间”(比如音乐播放同步),得换
CLOCK_MONOTONIC_RAW或专用音频时钟,但那已超出GetTimeMs()的定位
真正容易被忽略的是:别在循环里反复调用它来“忙等”,也别假设返回值绝对连续 —— 即便单调,中间也可能跳过若干毫秒(尤其在负载高或虚拟机中)。

















