How to get thread CPU utilization metrics in Redhat Linux

Rtan picture Rtan · Apr 19, 2009 · Viewed 14.7k times · Source

I need to get CPU utilization metrics for all the threads in a process.

  • Operating system = Redhat linux
  • programming language = C++ using POSIX
  • requirements = need to take samples every few seconds indefinetly, not just for one snapshot in time.
  • constraints = not allowed to write additional code in thread

    I know you can use the "top" command, but what other ways are there? Is there a flag for "ps"?

Thank you in advance for all your help.

Answer

freak picture freak · Apr 19, 2009

You can read the content of /proc/[your PID]/stat to get information for the whole process and if you have a 2.6 kernel there is also /proc/[your PID]/task/[thread ID]/stat with the information for the individual threads. (see here)

Specifically, you will find these two fields:

The number of jiffies that this process has been scheduled in user mode.

stime %lu

The number of jiffies that this process has been scheduled in kernel mode.

cutime %ld

The problematic part here is the unit in which the values are given. A jiffy is 1/HZ seconds, where HZ is the kernel clock tick rate and determining this clock rate is the hard part.

If you need this only for one specific system, you can just do some tests or look at your kernel headers and hardcode this value into your program. If you want to know how to determine it in a more general way, you can look at how a tool like top is doing it by looking at its source code (see the old_Hertz_hack() function and the related comments)