据我所知,Linux的起点CLOCK_MONOTONIC
是启动时间.在我目前的工作中,我更喜欢使用单调时钟而不是CLOCK_REALTIME
(用于计算)但同时我需要在报告中提供人性化的时间戳(年/月/日).它们可能不是很精确,所以我想加入单调计数器和启动时间.
从这里我可以使用api调用在linux系统上获得这个时间?
Vil*_*ray 11
假设Linux内核在开始跟踪单调时钟的同时启动正常运行时间计数器,您可以通过从当前时间减去正常运行时间来推导启动时间(相对于Epoch).
Linux 通过结构在几秒钟内提供系统正常运行时间sysinfo
; 可以通过该功能在POSIX兼容库上获取Epoch以来的当前时间(以秒为单位)time
.
#include <stddef.h>
#include <stdio.h>
#include <time.h>
#include <sys/sysinfo.h>
int main(void){
/* get uptime in seconds */
struct sysinfo info;
sysinfo(&info);
/* calculate boot time in seconds since the Epoch */
const time_t boottime = time(NULL) - info.uptime;
/* get monotonic clock time */
struct timespec monotime;
clock_gettime(CLOCK_MONOTONIC, &monotime);
/* calculate current time in seconds since the Epoch */
time_t curtime = boottime + monotime.tv_sec;
/* get realtime clock time for comparison */
struct timespec realtime;
clock_gettime(CLOCK_REALTIME, &realtime);
printf("Boot time = %s", ctime(&boottime));
printf("Current time = %s", ctime(&curtime));
printf("Real Time = %s", ctime(&realtime.tv_sec));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,单调时钟可能与启动时间不完全匹配.当我在我的机器上测试上面的代码时,单调时钟距离系统正常运行时间是第二次.但是,只要考虑相应的偏移量,您仍然可以使用单调时钟.
可移植性说明:虽然Linux可能会返回相对于启动时间的当前单调时间,但POSIX机器通常可以从任意 - 但一致 - 的时间点(通常是Epoch)返回当前的单调时间.
作为旁注,您可能不需要像我那样导出启动时间.我怀疑有一种方法可以通过Linux API获取启动时间,因为有许多Linux实用程序以人类可读的格式显示启动时间.例如:
$ who -b
system boot 2013-06-21 12:56
Run Code Online (Sandbox Code Playgroud)
我无法找到这样的调用,但检查这些常用实用程序的源代码可能会揭示它们如何确定人类可读的启动时间.
对于该who
实用程序,我怀疑它利用该utmp
文件来获取系统启动时间.
CLOCK_MONOTONIC
一般不会受到任何系统时间调整的影响。例如,如果系统时钟是通过 NTP 调整的,CLOCK_MONOTONIC
则无法知道(也不需要知道)。
因此,CLOCK_MONOTONIC
如果您需要人类可读的时间戳,请不要使用。
看到CLOCK_REALTIME 和 CLOCK_MONOTONIC 之间的区别吗?进行讨论。