cmultithreadinglinux-kernelcpu-usage

Can I measure the CPU usage in Linux by thread into application


I have the multi-threading C application (daemon). Can I measure the CPU usage by thread into my application.


Solution

  • While this is an old question it came up as the top related hit on my own Google search. So I'll provide the answer I came up with.

    Assuming you're using pthreads or a library that uses it, such as Boost libraries.

    You can use pthread_getcpuclockid and clock_gettime.
    Man page links pthread_getcpuclockid, clock_gettime.

    Here is a simple example that return the current time as a double.

    double cpuNow( void ) {
        struct timespec ts;
        clockid_t cid;
    
        pthread_getcpuclockid(pthread_self(), &cid);
        clock_gettime(cid, &ts);
        return ts.tv_sec + (((double)ts.tv_nsec)*0.000000001);
    }