Measuring context switch time for threads
<p>I want to calculate the context switch time and I am thinking to use mutex and conditional variables to signal between 2 threads so that only one thread runs at a time. I can use <code>CLOCK_MONOTONIC</code> to measure the entire execution time and <code>CLOCK_THREAD_CPUTIME_ID</code> to measure how long each thread runs.<br>
Then the context switch time is the <code>(total_time - thread_1_time - thread_2_time)</code>. 
To get a more accurate result, I can just loop over it and take the average.</p>

<p>Is this a correct way to approximate the context switch time?  I cant think of anything that might go wrong but I am getting answers that are under 1 nanosecond..</p>

<p>I forgot to mention that the more time I loop it over and take the average, the smaller results I get.</p>

<p><strong>Edit</strong></p>

<p>here is a snippet of the code that I have </p>

<pre><code>    typedef struct
    {
      struct timespec start;
      struct timespec end;
    }thread_time;

    ...


    // each thread function looks similar like this
    void* thread_1_func(void* time)
    {
       thread_time* thread_time = (thread_time*) time;

       clock_gettime(CLOCK_THREAD_CPUTIME_ID, &amp;(thread_time-&gt;start)); 
       for(x = 0; x &lt; loop; ++x)
       {
         //where it switches to another thread
       }
       clock_gettime(CLOCK_THREAD_CPUTIME_ID, &amp;(thread_time-&gt;end));

       return NULL;
   };

   void* thread_2_func(void* time)
   {
      //similar as above
   }

   int main()
   {
      ...
      pthread_t thread_1;
      pthread_t thread_2;

      thread_time thread_1_time;
      thread_time thread_2_time;

      struct timespec start, end;

      // stamps the start time 
      clock_gettime(CLOCK_MONOTONIC, &amp;start);

      // create two threads with the time structs as the arguments 
      pthread_create(&amp;thread_1, NULL, &amp;thread_1_func, (void*) &amp;thread_1_time);
      pthread_create(&amp;thread_2, NULL, &amp;thread_2_func, (void*) &amp;thread_2_time); 
      // waits for the two threads to terminate 
      pthread_join(thread_1, NULL);
      pthread_join(thread_2, NULL);

      // stamps the end time 
      clock_gettime(CLOCK_MONOTONIC, &amp;end);

      // then I calculate the difference between between total execution time and the total execution time of two different threads..
   }
</code></pre>