Search code examples
cmultithreadingtimepthreadstime-measurement

How do I measure time per thread in C?


I am working on a code with multiple number of threads and I want to print the time it took for me to complete task I assigned the i-th thread to do. Meaning I want to print the time each thread took to be done with the doSomeThing function

int main(int argc, char *argv[]){
   // ...
         i=0;
         while (i < NumberOfThreads){

              check = pthread_create(&(id_arr[i]), NULL, &doSomeThing, &data);

              i++;
         }
   // ...
}

void* doSomeThing(void *arg){
   // ...
}

if I add gettimeofday(&thread_start, NULL) before the pthread_create and then add gettimeofday(&thread_end, NULL) after the pthread_create, will I be actually measuring the time each thread took or just the time the main took? And if I put the gettimeofday inside the doSomething function wouldn't they create race-conditions?

If you have any idea on how to measure the time per thread please let me know, thank you.


Solution

  • You can certainly use gettimeofday inside the thread function itself. Using local (stack) variables is completely thread-safe - every thread runs on its own stack (by definition).

    void* doSomeThing(void *arg){
        struct timeval t0, t1, dt;
    
        gettimeofday(&t0, NULL);
    
        // do work
    
        gettimeofday(&t1, NULL);
    
        timersub(&t1, &t0, &dt);
    
        fprintf(stderr, "doSomeThing (thread %ld) took %d.%06d sec\n",
                   (long)pthread_self(), dt.tv_sec, dt.tv_usec);
    }
    

    If you put the same code around pthread_create(), you would only see the amount of time it took for the thread to be created, not executed. If pthread_create blocked until the thread completed, there would be no point in ever using threads!