1

I need to write script which returns file with information about cpu and memory usage of specified process through given time period. When I use ps -p pid I only get usage of one cpu core, and when I use top I get binary file as output. I tried with next :

    while :;
    top -n 1 -p pid | awk '{ print $9" "$10 }'
    sleep 10;
    done
skvo
  • 11
  • 2
  • 3
    Please see [this answer](http://stackoverflow.com/questions/16726779/how-do-i-get-the-total-cpu-usage-of-an-application-from-proc-pid-stat). This question has been asked before. – ojblass Nov 11 '15 at 23:06

2 Answers2

0

Information the kernel offers for your process is in the /proc filesystem. Primarily you would need to parse these two files to get the pertinent data for your script

/proc/(pid)/status
/proc/(pid)/stat

This thread describes getting this CPU data in detail so I wont here.

The problem I think you'll find is CPU usage for a process is not broken down into the various cores available on your system, but rather summarized into a number that approaches 100% * (number of cores). The closest to this is the "last processor used" column of top (option f, J), though this hardly addresses your problem. A profiling tool like the one in this thread is likely the final answer.

I don't know your environment or requrements; however a solution could be running only the process isolated on a machine, then collecting each cores CPU usage at the system level loosely representing the process demand.

Community
  • 1
  • 1
Josiah DeWitt
  • 1,594
  • 13
  • 15
0

Try this:

$PID=24748; while true; do CPU=$(ps H -q $PID -eo "pid %cpu %mem" | grep $PID | cut -d " " -f 3 | sed -e 's/$/\+/' | tr -d "\n" | sed -e 's/+$/\n/' | bc) && MEM=$(ps H -q $PID -eo "pid %cpu %mem" | grep $PID | cut -d " " -f 4 | head -n 1) && echo $PID $CPU $MEM && sleep 3; done

It basically just adds up the CPU % usage of each thread with bc, takes the memory usage (as a whole), and prints them, of a specified PID.

oxagast
  • 397
  • 1
  • 12