根据当前时间戳与机器启动至今的时间长度相减,可以精确计算出机器启动时刻的时间戳epochtime
代码
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <chrono>
int main()
{
#ifdef __linux
// linux only
std::cout << "=== linux only time analysis ===" << std::endl;
struct timespec timestamp = { 0, 0 };
clock_gettime(CLOCK_REALTIME, ×tamp);
uint64_t now_epoch_time = timestamp.tv_sec * 1000000000 + timestamp.tv_nsec;
std::cout << "current epoch time: " << now_epoch_time << " ns" << std::endl;
clock_gettime(CLOCK_MONOTONIC, ×tamp);
uint64_t machine_running_duration = timestamp.tv_sec * 1000000000 + timestamp.tv_nsec;
std::cout << "machine running to now duration: " << machine_running_duration << " ns" << std::endl;
uint64_t launch_epoch_time = now_epoch_time - machine_running_duration;
std::cout << "machine launch epoch time: " << launch_epoch_time << " ns" << std::endl;
#endif
// cross platform
std::cout << "=== cross platform time analysis ===" << std::endl;
auto now = std::chrono::system_clock::now(); // system_clock can get the current timestamp, accuracy to 1 ns in linux and 100 ns in win
long long now_timestamp = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch()).count(); // milliseconds, microseconds, nanoseconds, all are ok
std::cout << "current epoch time: " << now_timestamp << " ns" << std::endl;
long long duration = std::chrono::steady_clock::now().time_since_epoch().count(); // steady_clock can get maching running to now duration, accuracy to 1 ns
std::cout << "machine running to now duration: " << duration << " ns" << std::endl;
uint64_t launch_timestamp = now_timestamp - duration;
std::cout << "machine launch epoch time: " << launch_timestamp << " ns" << std::endl;
return 0;
}
结果
=== linux only time analysis ===
current epoch time: 1587539276554509088 ns
machine running to now duration: 13213451782940677 ns
machine launch epoch time: 1574325824771568411 ns
=== cross platform time analysis ===
current epoch time: 1587539276554564904 ns
machine running to now duration: 13213451782993731 ns
machine launch epoch time: 1574325824771571173 ns
- 有C++11的方法和linux only的方法
- 比shell的命令精度高,可以到纳秒
- 因为是epochtime,可以转换为自然时间格式
- 计算误差在纳秒级,建议多跑几次求平均
分类:
C++/C
, c++11/14/17/20
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
2013-11-28 关于初始化C++类成员
2013-11-28 TCP和UDP的"保护消息边界" (经典)
2013-11-28 (经典)tcp粘包分析
2013-11-28 解决TCP网络传输“粘包”问题
2013-11-28 无锁队列
2013-11-28 MFC全局函数开局——AfxGetApp解剖
2013-11-28 MFC的消息映射机制揭秘