POSIX 'CLOCK_REALTIME' 时钟是否应该引用 UTC 纪元?

Should the POSIX 'CLOCK_REALTIME' clock be referenced to the UTC epoch?

我正在使用 POSIX clock_gettime(CLOCK_REALTIME, &curr_time) 获取 CLOCK_REALTIME 时钟的当前时间。我了解 CLOCK_REALTIME 和 CLOCK_MONOTONIC 之间的区别。但是,我不知道的是与 CLOCK_REALTIME.

相关的纪元

我的第一个猜测是它是自 UTC 纪元以来经过的 seconds/nanoseconds。但是,我得到的值是 ~180000 秒,也就是 ~50 小时。显然不是自 UTC 纪元以来经过的时间。

所以我的问题是:CLOCK_REALTIME 引用的是什么?重启?特定于平台? UTC 而我只是做错了什么?

谢谢,

CLOCK_REALTIME 与 Unix 纪元相关("UTC epoch" 是同一件事,但不是正确的命名方式。它只是 UTC 时区中的 Unix 纪元)。

试试这个代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

int main(void)
{
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    printf("%ld\n", ts.tv_sec);
    exit(0);
}

POSIX specification for clock_gettimeCLOCK_REALTIME 的零点定义为 "the Epoch":

All implementations shall support a clock_id of CLOCK_REALTIME as defined in <time.h>. This clock represents the clock measuring real time for the system. For this clock, the values returned by clock_gettime() and specified by clock_settime() represent the amount of time (in seconds and nanoseconds) since the Epoch.

它在 "General Concepts" chapter, section 4.16:

中定义了术语 "the Epoch"

A Coordinated Universal Time name (specified in terms of seconds (tm_sec), minutes (tm_min), hours (tm_hour), days since January 1 of the year (tm_yday), and calendar year minus 1900 (tm_year)) is related to a time represented as seconds since the Epoch, according to the expression below.

If the year is <1970 or the value is negative, the relationship is undefined. If the year is >=1970 and the value is non-negative, the value is related to a Coordinated Universal Time name according to the C-language expression, where tm_sec, tm_min, tm_hour, tm_yday, and tm_year are all integer types:

tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
    (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
    ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400

如果您将该表达式放在等式的一侧,将零放在另一侧,并加上通常对日期、小时、分钟、秒的范围的限制,您会发现 "the Epoch" 对应于 ISO 日历日期 1970-01-01T00:00:00Z。为什么他们不直接这么说,我不知道。


您观察到的现象,其中 clock_gettime(CLOCK_REALTIME) 产生了自 1970-01-01T00:00:00Z 以来大约 50 小时的值,在 POSIX 第 4 章的下一句中说明:

The relationship between the actual time of day and the current value for seconds since the Epoch is unspecified.

也就是说,POSIX不需要您的计算机时钟准确。