/* A periodic real-time task, the core of most control loops.
   It wakes up every millisecond and measures how late each wake-up was.
   Run it with a real-time priority and compare:
     cc -O2 -o cyclic cyclic.c
     ./cyclic                 normal priority (SCHED_OTHER)
     chrt -f 80 ./cyclic      SCHED_FIFO priority 80
   On a PREEMPT_RT kernel the worst case stays small even when the machine is busy.
*/
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <sys/mman.h>
#include <time.h>

#define PERIOD_NS 1000000L /* 1 ms */
#define LOOPS 1000

static long late_us(struct timespec now, struct timespec due) {
    return ((now.tv_sec - due.tv_sec) * 1000000000L + (now.tv_nsec - due.tv_nsec)) / 1000;
}

int main(void) {
    /* Keep all memory in RAM, so a page fault can't make a wake-up late. */
    if (mlockall(MCL_CURRENT | MCL_FUTURE) != 0) printf("note: couldn't lock memory, so page faults may add delay\n");

    int policy = sched_getscheduler(0);
    struct sched_param sp;
    sched_getparam(0, &sp);
    printf("policy %s, priority %d, period %ld us, %d loops\n",
           policy == SCHED_FIFO ? "SCHED_FIFO" : policy == SCHED_RR ? "SCHED_RR" : "SCHED_OTHER",
           sp.sched_priority, PERIOD_NS / 1000, LOOPS);

    struct timespec due, now;
    clock_gettime(CLOCK_MONOTONIC, &due);
    long min = 1000000, max = 0, total = 0;
    for (int i = 0; i < LOOPS; i++) {
        due.tv_nsec += PERIOD_NS;
        while (due.tv_nsec >= 1000000000L) {
            due.tv_nsec -= 1000000000L;
            due.tv_sec++;
        }
        /* Sleep until an absolute time, so small delays don't add up. */
        clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &due, NULL);
        clock_gettime(CLOCK_MONOTONIC, &now);
        long late = late_us(now, due);
        if (late < min) min = late;
        if (late > max) max = late;
        total += late;
    }
    printf("wake-up latency: min %ld us, avg %ld us, max %ld us\n", min, total / LOOPS, max);
    return 0;
}
