C++獲取機器啓動至今的時長和機器啓動的時間戳

根據當前時間戳與機器啓動至今的時間長度相減,可以精確計算出機器啓動時刻的時間戳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,可以轉換爲自然時間格式
  • 計算誤差在納秒級,建議多跑幾次求平均
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章