title: What is the best way to measure total context switches in a C/C++ application?
body: <p>This is simple way I am trying to get the resource usage, specially total context switches that happen in the execution of the program. </p>
  
  <pre><code>#include&lt;stdio.h&gt;
  #include &lt;sys/resource.h&gt;
  
  int appgetrusage(struct rusage *);
  int appgetdiffrusage(struct rusage *, struct rusage *);
  
  int main() {
      struct rusage begin, end;
  
      appgetrusage(&amp;begin);
  
  /*
  * core of the program goes here 
  * where lot of system threads are spawned and joined
  *
  */
  
      appgetrusage(&amp;end);
      appgetdiffrusage(&amp;begin, &amp;end);
  
      return 0;
  }
  
  
  int appgetrusage(struct rusage *usage){
      int who = RUSAGE_SELF;
      struct timeval start, end;
      getrusage(RUSAGE_SELF, usage);
      return 1;
  }
  
  
  int appgetdiffrusage(struct rusage *oldr, struct rusage *newr){
  
      printf("\n");    
      printf("user time (ms): %llu\n",1000 * ((newr-&gt;ru_utime).tv_sec - (oldr-&gt;ru_utime).tv_sec) + 
              ((newr-&gt;ru_utime).tv_usec - (oldr-&gt;ru_utime).tv_usec) / 1000);
  
      printf("system time (ms): %ld\n", 1000 * ((newr-&gt;ru_stime).tv_sec - (oldr-&gt;ru_stime).tv_sec) + 
              ((newr-&gt;ru_stime).tv_usec - (oldr-&gt;ru_stime).tv_usec) / 1000);         
  
      printf("voluntary context switches : %ld\n", newr-&gt;ru_nvcsw - oldr-&gt;ru_nvcsw);
      printf("involuntary context switches : %ld\n", newr-&gt;ru_nivcsw - oldr-&gt;ru_nivcsw);
  
      return 1;
  }
  </code></pre>
  
  <ol>
  <li>Is this the right approach?</li>
  <li>Can anybody suggest an alternative? or Corrections? :-)</li>
  </ol>