如@zwol 的回答所示,事情确实变得有点复杂和有趣--
请参阅以下简单程序 (foo.c):
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int
main()
{
struct timespec spec;
printf("_POSIX_MONOTONIC_CLOCK = %d\n",
(int)_POSIX_MONOTONIC_CLOCK);
printf("sysconf(_SC_MONOTONIC_CLOCK) = %ld\n",
sysconf(_SC_MONOTONIC_CLOCK) );
printf("clock_gettime(CLOCK_MONOTONIC) = %d\n",
clock_gettime(CLOCK_MONOTONIC, & spec) );
return 0;
}
在 Linux(Debian 9、x86_64)上:
[STEP 101] # uname -a
Linux debian9 4.9.0-6-amd64 #1 SMP Debian 4.9.88-1 (2018-04-29) x86_64 GNU/Linux
[STEP 102] # gcc foo.c && ./a.out
_POSIX_MONOTONIC_CLOCK = 0
sysconf(_SC_MONOTONIC_CLOCK) = 200809
clock_gettime(CLOCK_MONOTONIC) = 0
[STEP 103] #
在 macOS(10.13,High Sierra)上:
[STEP 201] $ uname -a
Darwin macbook.home 17.5.0 Darwin Kernel Version 17.5.0: Fri Apr 13 19:32:32 PDT 2018; root:xnu-4570.51.2~1/RELEASE_X86_64 x86_64
[STEP 202] $ cc foo.c && ./a.out
_POSIX_MONOTONIC_CLOCK = -1
sysconf(_SC_MONOTONIC_CLOCK) = -1
clock_gettime(CLOCK_MONOTONIC) = 0
[STEP 203] $
在 FreeBSD(11.1,x86_64)上:
[STEP 301] # uname -a
FreeBSD freebsd 11.1-RELEASE FreeBSD 11.1-RELEASE #0 r321309: Fri Jul 21 02:08:28 UTC 2017 root@releng2.nyi.freebsd.org:/usr/obj/usr/src/sys/GENERIC amd64
[STEP 302] # cc foo.c && ./a.out
_POSIX_MONOTONIC_CLOCK = 200112
sysconf(_SC_MONOTONIC_CLOCK) = 200112
clock_gettime(CLOCK_MONOTONIC) = 0
[STEP 303] #
macOS 上的结果让我很惊讶。 sysconf() 返回 -1 但 clock_gettime(CLOCK_MONOTONIC) 成功!不确定这是否表明 macOS 不符合 POSIX。无论如何,它证明 使用 sysconf() 进行运行时检查是不可靠的!
最后我要这样做了:
int
Clock_gettime(struct timespec * spec)
{
static bool firstime = true;
static clockid_t clock = CLOCK_REALTIME;
if (firstime) {
firstime = false;
#ifdef CLOCK_MONOTONIC
if (clock_gettime(CLOCK_MONOTONIC, spec) == 0) {
clock = CLOCK_MONOTONIC;
return 0;
}
#endif
}
return clock_gettime(clock, spec);
}