Sunday, April 11, 2010

Measure CPU usage time by Thread

    On Linux there are two commands you can use to measure CPU usage time of a thread in a multi threaded application.  Those commands are getrusage() and clock_gettime().  You can sue same commands to measure CPU time consumed by process.

Sample program to measure CPU time in a thread is given below:



#include
#include
#include


    int kResult = 0;
    struct rusage start, end;
    struct timeval timeS, timeE;
    double t= 0.0, time= 0.0;

    struct timespec st, endt;
    double t1= 0.0, time1= 0.0;

    // measure CPU time
      kResult = getrusage(RUSAGE_THREAD, &start);

        if (kResult == -1)
            fprintf(stderr, "\n\n Error in getrusage command");

        timeS = start.ru_stime; // system time
        t = (double)timeS.tv_sec + (double) timeS.tv_usec / 1000000.0;
        timeS = start.ru_utime; // user time
        t = t + (double)timeS.tv_sec + (double) timeS.tv_usec / 1000000.0;

        kResult = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &st);
        if (kResult == -1)
            fprintf(stderr, "\n\n Error in clock_gettime command");
      
        t1 = (double) (st.tv_sec * 1000000.0 )+ (double) st.tv_nsec / 1000.0 ;
  


   // Do some operation to consume CPU


  // measure CPU time

 kResult = getrusage(RUSAGE_THREAD, &end);

        if (kResult == -1)
            fprintf(stderr, "\n\n Error in getrusage command");

        timeE = end.ru_stime; // system time
        time = (double)timeE.tv_sec + (double) timeE.tv_usec / 1000000.0;
        timeE = end.ru_utime; // user time
        time = time + (double)timeE.tv_sec + (double) timeE.tv_usec / 1000000.0;

        time = time - t;
        fprintf(stderr,"\n\n Total CPU usage time using 'getrusage' = %.12lf\n\n", time);

        kResult = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &endt);
        if (kResult == -1)
            fprintf(stderr, "\n\n Error in clock_gettime command");
        
        time1 = (double) (endt.tv_sec * 1000000.0)+ (double) endt.tv_nsec / 1000.0 ;
        time1 = (time1 - t1) / 1000000.0;

        fprintf(stderr,"\n\n Total CPU usage time using 'clock_gettime' = %.12lf\n\n", time1);



Note: clock_gettime will generate error if you will not provide -lrt library to linker.