1

I would like to know if a program / a thread was dispatched / scheduled in C under Linux and if possible how often. The reason is that I'm measuring the runtime of a loop and want to prevent false results.

This is a minimal example:

#include <stdio.h>

int times_dispatched() {
    // how to check?
    return 0;
}

int main() {
    int i, dummy = 0;
    for(i=0; i<10000000; i++) {
        dummy++;
    }

    printf("counted to %d; program was dispatched %d times\n", dummy, times_dispatched());
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Thomas Rebele
  • 374
  • 3
  • 11
  • that busy wait loop looks terrible. Use sleep() instead. –  Aug 06 '12 at 18:59
  • Have a look at this question: http://stackoverflow.com/questions/2040257/measuring-amount-of-cpu-time-taken-by-a-piece-of-code-in-c-on-unix-linux – Eric Petroelje Aug 06 '12 at 19:01

1 Answers1

1

On Linux you can use getrusage function.

#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>

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 <stdlib.h>
#include <stdio.h>

#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.

Eldar Abusalimov
  • 24,387
  • 4
  • 67
  • 71