title: pthread execution time ? How to calculate?
body: <p>In my application, i  need to calculate each  thread's  execution time [ literally time it has taken from starting of the pthread and its execution termination]. Termination can be of type 'pthread_exit' or explicit cancellation.  In the following code, i have used pthread specfic data to retain the starting time of each thread, and hence i could find the total time. Do you guys think the following approach makes sense? IF NOT,  input is really appreciated!!!. For testing purpose, thread cancels by itself after some period of sleep. </p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  
  typedef struct _pTime
  {
      time_t stime;
  }pTime;
  
  pthread_key_t kstime;
  
  void   cancelRoutine (void * arg)
  {
      pTime etime, *btime;
      time (&amp;(etime.stime));
      printf (" Inside cancelRoutine ...tid: %l \n", pthread_self());
      btime = (pTime *) pthread_getspecific (kstime);
      printf ("Time taken :  %lf ", difftime (etime.stime, btime-&gt;stime));
  }
  
  void * tfunction ( void * arg)
  {
      int waitTime = (int) arg;
      printf ("\n Wait Time is %ud ", waitTime);
      pTime  *start;
      start = (pTime *) malloc (sizeof (pTime));
      time (&amp;(start-&gt;stime));
  
      pthread_setspecific (kstime, start);
      pthread_cleanup_push (cancelRoutine, NULL);
      printf (" Invoking the  thread \n");
      /* Doing Certain Work here */
      sleep (waitTime);
      pthread_cancel ( pthread_self());
      sleep(waitTime);
      pthread_cleanup_pop (NULL);
  }
  
  int main ( int argc, char **argv)
  {
      pthread_t tid[2];
      int toBeSpend=10, i;
      pthread_key_create(&amp;kstime, NULL);
  
      for (i=0; i&lt;2; i++)
          pthread_create (&amp;tid[i], NULL, tfunction, (void *)(toBeSpend*(i+1)));
      sleep (3);
      for(i=0; i&lt;2; i++)
          pthread_join (tid[i], NULL);
  }
  </code></pre>