DoubleLi

qq: 517712484 wx: ldbgliet

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  4737 随笔 :: 2 文章 :: 542 评论 :: 1615万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

根据当前时间戳与机器启动至今的时间长度相减,可以精确计算出机器启动时刻的时间戳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, &timestamp);
	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, &timestamp);
	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,可以转换为自然时间格式
  • 计算误差在纳秒级,建议多跑几次求平均
 
posted on   DoubleLi  阅读(237)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源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的消息映射机制揭秘
点击右上角即可分享
微信分享提示