Are there any well-behaved POSIX interval timers?

前端 未结 4 763
别跟我提以往
别跟我提以往 2020-12-14 08:58

Inspired by the last leap second, I\'ve been exploring timing (specifically, interval timers) using POSIX calls.

POSIX provides several ways to set up timers, but th

4条回答
  •  鱼传尺愫
    2020-12-14 09:24

    You can look at the question here for clock_gettime emulation, which I've also supplied an answer for, but helped me as well. I've recently added a simple timer to a little repository I keep for Mac OS X timing that partially emulates POSIX calls. A simple test runs the timer at 2000Hz. The repo is called PosixMachTiming. Try it out.

    PosixMachTiming is based on Mach. It seems some of the timing-related Mach API has disappeared from Apple's pages and has deprecated, but there are still bits of source code floating around. It looks like AbsoluteTime units and kernel abstractions found here are the new way of doing things. Anyways the PosixMachTiming repo still works for me.

    Overview of PosixMachTiming

    clock_gettime is emulated for CLOCK_REALTIME by a mach function calls that tap into the system realtime clock, dubbed CALENDAR_CLOCK.

    The clock_gettime is emulated for CLOCK_MONOTONIC by using a global variable (extern mach_port_t clock_port). This clock is initialized when the computer turns on or maybe wakes up. I'm not sure. In any case, it's the global variable that the function mach_absolute_time() calls.

    clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, ...) is emulated by using nanosleep on the difference between current time and the absolute monotonic time.

    itimer_start() and itimer_step() are based on calling clock_nanosleep for a target absolute monotonic time. It increments the target time by the time-step at each iteration (not the current time) so that clock skew is not an issue.

    Note that this does not satisfy your requirement to be able to support multiple timers in the same process.

提交回复
热议问题