ns-precision monotonic clock in C on Linux and OS X

后端 未结 2 409
再見小時候
再見小時候 2021-01-06 10:38

clock_gettime(CLOCK_MONOTONIC, ...) is available in Linux but not OS X. The Mach timers are available in OS X but not in Linux.

How can I get a ns-preci

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 11:38

    I used the answer by Douglas (accepted answer), his references and other examples floating around the internet (such as this question).

    This answer is to include my version of the code which emulates the clock_gettime for CLOCK_REALTIME and CLOCK_MONOTONIC. It also emulates the function clock_nanosleep() for absolute monotonic time. The code is hosted on GitHub here.

    For it to work, the only additional bit needed in your code is

    #ifdef __MACH__
    timing_mach_init();
    #endif
    

    then use clock_gettime() and clock_nanosleep_abstime() as if you were using a system that is actually POSIX compliant (with realtime extensions).

提交回复
热议问题