Linux – How to check libraries’s CPU utilization in linux

centoscentral-processing-unitlinuxmonitoring

I'm having a high CPU utilization, Is there any way to identify which part of my Program is using more CPU. Its a program written in C++, running on a CENTOS 5 box.

I'm suspecting the problem high usage is in shared libraries, but how can I monitor how much CPU all the shared libraries are using?

Best Answer

You can try using ltrace with the -c trace (very similar to strace but for library calls instead of system calls). This won't be complete as actually profiling the code and might not be the CPU time breakdown you are looking for, but it might just be the quick syadmin level tool you need.

kbrandt@kbrandt-acer:~$ ltrace -c xcalc
% time     seconds  usecs/call     calls      function
------ ----------- ----------- --------- --------------------
 66.83    0.222693        4453        50 XtCreateManagedWidget
 28.52    0.095048       95048         1 XtAppInitialize
  0.85    0.002837        2837         1 XtRealizeWidget
  0.83    0.002764        2764         1 XSetWMProtocols
  0.77    0.002581        2581         1 XtGetApplicationResources
  0.42    0.001383          53        26 XtWindow
  0.41    0.001371          54        25 XtDisplay
...
------ ----------- ----------- --------- --------------------
100.00    0.333219                   168 total

strace also with the -c switch will give you similar output but will show the system calls (the calls the libraries are using -- so sort of a level deeper).

The caveat with both of these break downs is these are wall clock time spent on each call and it doesn't show if this was active or idle time.

If you have the code and want to go all out you want code profiling. Stack Overflows "What can I use to profile my C++ code in Linux?" should get you started. I have used Valgrind with C code and liked it.