Search code examples
c++linuxtimeroverhead

Implementing a low-overhead interval timer with C++ in Linux


I am trying to implement a background user-space program that will perform various tasks and calculations every 100ms in Linux. I can do this by using the alarm signal in Linux and the following structure is the way I implemented my interval timer.

void timer_handler (int signum){
    printf("In timer handler!\n");
}

int main (){

    struct sigaction s_action;
    struct itimerval timer;

    /* Set Up a Timer */
    /* Install timer_handler as the signal handler for SIGVTALRM. */
    memset (&s_action, 0, sizeof (s_action));
    s_action.sa_handler = &timer_handler;
    sigaction (SIGVTALRM, &s_action, NULL);

    /* Timer configuration for 100ms */
    timer.it_value.tv_sec = 0;
    timer.it_value.tv_usec = 100000;
    timer.it_interval.tv_sec = 0;
    timer.it_interval.tv_usec = 100000;

    /* Set up the timer */
    setitimer (ITIMER_VIRTUAL, &timer, NULL);

    while(1);
}

This approach, however, does not seem to be the optimal way of doing (in terms of performance) this because of the infinite loop. It significantly increases CPU utilization. Once it starts running in the background, the performance of my other programs degrades by as mush as 15%.

What I would ideally want is to have a program that, unless a timer interrupt occurs, will keep sleeping. Multi-threading seems to be an option but I am not very experienced with that subject. I would appreciate any suggestions or pointers on how to implement such program with minimal overhead.


Solution

  • Read time(7), signal(7), timerfd_create(2), poll(2), nanosleep(2) and Advanced Linux Programming.

    Your signal handler is incorrect (it should not call printf; it could write).

    You could have

    while(1) poll(NULL, 0, 1);
    

    but probably a real event loop using poll on a file descriptor initialized with timerfd_create should be better.

    I assume of course that you are fairly confident that every periodic task lasts much less than the period. (e.g. that each task needs no more than 50 milliseconds but has a 100 millisecond period).