fork download
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <sys/types.h>
  4. #include <sys/time.h>
  5. #include <sys/resource.h>
  6.  
  7. #define LOOPS 100000000
  8.  
  9. static void loop(volatile unsigned int count) {
  10. while(count--) { }
  11. }
  12.  
  13. static int times_dispatched(long *vol, long *invol) {
  14. struct rusage usage;
  15. int err;
  16.  
  17. if ((err = getrusage(RUSAGE_SELF, &usage)) != 0) {
  18. return err;
  19. }
  20.  
  21. *vol = usage.ru_nvcsw;
  22. *invol = usage.ru_nivcsw;
  23.  
  24. return 0;
  25. }
  26.  
  27. int main(void) {
  28. long vol, invol;
  29.  
  30. loop(LOOPS);
  31.  
  32. if (times_dispatched(&vol, &invol) != 0) {
  33. fprintf(stderr, "Unable to get dispatch stats");
  34. exit(1);
  35. }
  36. printf("Context switches: %ld voluntarily, %ld involuntarily\n",
  37. vol, invol);
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0.28s 1720KB
stdin
Standard input is empty
stdout
Context switches: 3 voluntarily, 283 involuntarily