Linux' hrtimer - microsecond precision?

前端 未结 2 1899
感动是毒
感动是毒 2021-01-03 03:21

Is it possible to execute tasks on a Linux host with microsecond precision? I.e., I\'d like to execute a task at a specific instant of time. I know, Linux is no real-time sy

相关标签:
2条回答
  • You can do what you want from user space

    1. use clock_gettime() with CLOCK_REALTIME to get the time-of-day with nano-second resolution
    2. use nanosleep() to yield the CPU until you are close to the time you need to execute your task (it is at least milli-second resolution).
    3. use a spin loop with clock_gettime() until you reach the desired time
    4. execute your task

    The clock_gettime() function is implemented as a VDSO in recent kernels and modern x86 processors - it takes 20-30 nanoseconds to get the time-of-day with nano-second resolution - you should be able to call clock_gettime() over 30 times per micro-second. Using this method your task should dispatch within 1/30th of a micro-second of the intended time.

    0 讨论(0)
  • 2021-01-03 03:54

    The default Linux kernel timer ticks each millisecond. Microseconds is way beyond anything current user hardware is capable of.

    The jitter you see is due to a host of factors, like interrupt handling and servicing higher priority tasks. You can cut that down somewhat by selecting hardware carefully, only enabling what is really needed. The real-time patchseries to the kernel (see the HOWTO) might be an option to reduce it a bit further.

    Always keep in mind that any gain has a definite cost in terms of interactiveness, stability, and (last, but by far not least) your time in building, tuning, troubleshooting, and keeping the house of cards from falling apart.

    0 讨论(0)
提交回复
热议问题