Question

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

Was it helpful?

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);
}

OTHER TIPS

You can parse out the data from /proc/<PID>/stat. The CPU line looks like this:-

cpu  143359 8217 480152 132054567 45162 5678 24656 0 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top