#include <why-time.h>
#include <iostream>
#include <sys/mman.h>
#include <unistd.h>

int main()
{
    if (geteuid() == 0)  {                             // running as root
        int error = mlockall(MCL_CURRENT|MCL_FUTURE);  // defend address space against swapping
        if (error == -1) {
            perror("mlockall");
            return 1;
        }
    }

    const Why::TimeSpec one_ms(0, 1'000'000);
    unsigned int num_rt_glitches = 0;
    
    while (true) {
        // perform work that fits in a 1ms (1000 writes should be ok)
        Why::TimeSpec before = Why::now_monotonic();
        {
            for (uint64_t i=0; i<500'000; i++)
                [[maybe_unused]] volatile int something = 42;
        }
        Why::TimeSpec after = Why::now_monotonic();

        auto time_taken = after - before;
        if (time_taken <= one_ms)
            Why::sleep(one_ms - time_taken);
        else
            std::cout << "RT-OOPS #" << ++num_rt_glitches << " "
                "(took " << time_taken.to_seconds()*1000.0 << " ms)" << std::endl;
    }
    return 0;
}
