C++获取机器启动至今的时长和机器启动的时间戳

发布时间 2023-11-28 10:40:50作者: DoubleLi

根据当前时间戳与机器启动至今的时间长度相减,可以精确计算出机器启动时刻的时间戳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,可以转换为自然时间格式
  • 计算误差在纳秒级,建议多跑几次求平均