CLOCK_MONOTONIC的起点

时间:2013-02-06 10:11:35

标签: linux real-time

正如我在Linux上所理解的那样,CLOCK_MONOTONIC的起点是启动时间。在我目前的工作中,我更喜欢使用单调时钟而不是CLOCK_REALTIME(用于计算),但同时我需要在报告中提供人性化的时间戳(年/月/日)。它们可能不是很精确,所以我想加入单调计数器和开机时间。

从这里我可以使用api调用在linux系统上获得这个时间?

3 个答案:

答案 0 :(得分:11)

假设Linux内核在开始跟踪单调时钟的同时启动 uptime 计数器,您可以通过减去正常运行时间来推导启动时间(相对于Epoch) 当前时间

Linux通过sysinfo结构在几秒钟内提供系统正常运行时间; 当前时间以秒为单位,因为可以通过time函数在符合POSIX的库上获取Epoch。

#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;
}

不幸的是,单调时钟可能与启动时间不完全匹配。当我在我的机器上测试上面的代码时,单调时钟距离系统正常运行时间是第二次。但是,只要考虑相应的偏移量,您仍然可以使用单调时钟。

可移植性注释 :虽然Linux可能会返回相对于启动时间的当前单调时间,但一般来说POSIX机器可以从任意方式返回当前的单调时间 - - 但一致 - 时间点(通常是大纪元)。


作为旁注,您可能不需要像我那样导出启动时间。我怀疑有一种方法可以通过Linux API获取启动时间,因为有许多Linux实用程序以人类可读的格式显示启动时间。例如:

$ who -b
         system boot  2013-06-21 12:56

我无法找到这样的调用,但检查其中一些常用实用程序的源代码可能会揭示它们如何确定人类可读的启动时间。

对于who实用程序,我怀疑它使用utmp文件来获取系统启动时间。

答案 1 :(得分:3)

http://www.kernel.org/doc/man-pages/online/pages/man2/clock_getres.2.html

  CLOCK_MONOTONIC
          Clock that cannot be set and represents monotonic time since some
          unspecified starting point.

意味着您可以使用CLOCK_MONOTONIC进行区间计算和其他事情,但您无法将其真正转换为人类可读的表示形式。

此外,您可能希望CLOCK_MONOTONIC_RAW而不是CLOCK_MONOTONIC

  CLOCK_MONOTONIC_RAW (since Linux 2.6.28; Linux-specific)
          Similar  to  CLOCK_MONOTONIC, but provides access to a raw hard‐
          ware-based time that is not subject to NTP adjustments.

继续使用CLOCK_REALTIME进行人类可读时间。

答案 2 :(得分:0)

CLOCK_MONOTONIC通常不受系统时间调整的影响。例如,如果通过NTP调整系统时钟,CLOCK_MONOTONIC无法知道(也不需要)。

因此,如果您需要人类可读的时间戳,请不要使用CLOCK_MONOTONIC

请参阅Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?进行讨论。

相关问题