Kyle
Kyle

Reputation: 154

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.

Upvotes: 1

Views: 7451

Answers (2)

Hans Kl&#252;nder
Hans Kl&#252;nder

Reputation: 2292

gettimeofday() measures elapsed time. If you want to measure CPU time, try this:

#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/stdint.h>

uint64_t time_used ( ) {
   struct rusage ru;
   struct timeval t;
   getrusage(RUSAGE_THREAD,&ru);
   t = ru.ru_utime;
   return (uint64_t) t.tv_sec*1000 + t.tv_usec/1000;
}

...

uint64_t t1, t2;
t1 = time_used();
... do some work ...
t2 = time_used();
printf("used %d milliseconds\n",(unsigned)(t2-t1));

You will have to do that inside the thread. This is an example. Search time_used

Jonathon Reinhart uses timersub(), which simplifies things. I merge that in here:

void time_used ( struct timeval *t ) {
   struct rusage ru;
   getrusage(RUSAGE_THREAD,&ru);
   *t = ru.ru_utime;
}

...

struct timeval t0, t1, dt;
time_used(&t0);
... do some work ...
time_used(&t1);
timersub(&t1, &t0, &dt);

printf("used %d.%06d seconds\n", dt.tv_sec, dt.tv_usec);

Upvotes: 2

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

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!

Upvotes: 2

Related Questions