如何检查系统是否支持“单调时钟"? [英] How to check if the system supports "Monotonic Clock"?
问题描述
我需要处理代码中的超时情况,并且如果系统支持单调时钟,则想使用clock_gettime(CLOCK_MONOTONIC)
.
#ifdef CLOCK_MONOTONIC
clock_gettime(CLOCK_MONOTONIC, & spec);
#else
clock_gettime(CLOCK_REALTIME, & spec);
#endif
我不确定这是否足够.也就是说,系统是否可能定义CLOCK_MONOTONIC
而不真正支持单调时钟?还是检查单调时钟是否受支持的可靠方法是什么?
每个POSIX的字母实际上都可能需要运行时测试,即使定义了常量CLOCK_MONOTONIC
也是如此.处理此问题的官方方法是使用_POSIX_MONOTONIC_CLOCK
功能测试宏",但是这些宏的语义确实很复杂:引用 解决方案
Per the letter of POSIX, you may in fact need a runtime test even if the constant CLOCK_MONOTONIC
is defined. The official way to handle this is with the _POSIX_MONOTONIC_CLOCK
"feature-test macro", but those macros have really complicated semantics: quoting http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/unistd.h.html ,
If a symbolic constant is not defined or is defined with the value -1, the option is not supported for compilation. If it is defined with a value greater than zero, the option shall always be supported when the application is executed. If it is defined with the value zero, the option shall be supported for compilation and might or might not be supported at runtime.
Translating that three-way distinction into code would give you something like this:
#if !defined _POSIX_MONOTONIC_CLOCK || _POSIX_MONOTONIC_CLOCK < 0
clock_gettime(CLOCK_REALTIME, &spec);
#elif _POSIX_MONOTONIC_CLOCK > 0
clock_gettime(CLOCK_MONOTONIC, &spec);
#else
if (clock_gettime(CLOCK_MONOTONIC, &spec))
clock_gettime(CLOCK_REALTIME, &spec));
#endif
But it's simpler and more readable if you just always do the runtime test when CLOCK_MONOTONIC itself is defined:
#ifdef CLOCK_MONOTONIC
if (clock_gettime(CLOCK_MONOTONIC, &spec))
#endif
clock_gettime(CLOCK_REALTIME, &spec);
This increases the size of your code by some trivial amount on current-generation OSes that do support CLOCK_MONOTONIC
, but the readability benefits are worth it in my opinion.
There is also a pretty strong argument for using CLOCK_MONOTONIC
unconditionally; you're more likely to find an OS that doesn't support clock_gettime
at all (e.g. MacOS X still doesn't have it as far as I know) than an OS that has clock_gettime
but not CLOCK_MONOTONIC
.
这篇关于如何检查系统是否支持“单调时钟"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!