Is it possible to check if (and how often) a program was dispatched/scheduled in C under Linux-Collection of common programming errors

On Linux you can use getrusage function.

#include 
#include 
#include 

int times_dispatched(long *vol, long *invol) {
    struct rusage usage;
    int err;

    if ((err = getrusage(RUSAGE_SELF, &usage)) != 0) {
        return err;
    }

    *vol   = usage.ru_nvcsw;
    *invol = usage.ru_nivcsw;

    return 0;
}

Test application:

#include 
#include 

#define LOOPS 100000000

static void loop(volatile unsigned int count) {
    while(count--) { }
}

int main(void) {
    long vol, invol;

    loop(LOOPS);

    if (times_dispatched(&vol, &invol) != 0) {
        fprintf(stderr, "Unable to get dispatch stats");
        exit(1);
    }
    printf("Context switches: %ld voluntarily, %ld involuntarily\n",
        vol, invol);

    return 0;
}

Output from Ideone:

Context switches: 3 voluntarily, 283 involuntarily

P.S. I wonder why it shows non-zero voluntary switches, may be that is because of using Ideone… On my desktop it is always zero, as expected.