How to get thread CPU utilization metrics in Redhat Linux
Asked Answered
G

4

8

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.

Gaspard answered 19/4, 2009 at 17:43 Comment(0)
T
8

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)

Taw answered 19/4, 2009 at 19:13 Comment(2)
I found out a way to get Hz value on a particular machine : cat /boot/config-uname -r | grep HZMaher
You can get the mentioned HZ value using this tool: getconf CLK_TCK. I am not sure how to get the value directly in a C program without calling an external tool.Townshend
D
1

Possibly a simpler way of doing this is to use getrusage with the linux specific extension of RUSAGE_THREAD. Once you have these times, you can just subtract the times the last time you sampled, and divide by the real time that passed since your last sample. That say you get the CPU usage as a percentage.

For linux specific documentation, see the rusage liunx man page.

Disproof answered 17/10, 2011 at 17:3 Comment(0)
D
0

You may be able to do this with gnu gprof which is available in Linux. I believe that they claim to support threading, but this is more complicated than profiling at the process level, so you may not get the results you're looking for.

Here's a howto for your situation.

Drudgery answered 19/4, 2009 at 17:47 Comment(0)
B
0

you can use "top" command to find the process Id first.

After that, you can use the following command to only display CPU/Memory usage for the process

top -p {pid}

After that, you can press "Shift"+"h" to show the threads

Bedding answered 18/8, 2016 at 14:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.