-3

How can I get the CPU % consumed by a Linux process with PHP or by bash? I tried to find any utility for this but couldn't. All I found was always getting the same result for same reason.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 7
    Possible duplicate of [php script to get cpu utilization for each process?](http://stackoverflow.com/questions/22833547/php-script-to-get-cpu-utilization-for-each-process) – Ravi Hirani Oct 18 '16 at 13:13
  • This link is talking about Windows and grabs a list of tasks, What I want is to give only the CPU utilization per process. – Ahmad Abdelwahed Oct 18 '16 at 17:54

1 Answers1

1

I found this amazing answer here: https://unix.stackexchange.com/questions/554/how-to-monitor-cpu-memory-usage-of-a-single-process

To use that information on a script you can do this:

calcPercCpu.sh

#!/bin/bash
nPid=$1;
nTimes=10; # customize it
delay=0.1; # customize it
strCalc=`top -d $delay -b -n $nTimes -p $nPid \
  |grep $nPid \
  |sed -r -e "s;\s\s*; ;g" -e "s;^ *;;" \
  |cut -d' ' -f9 \
  |tr '\n' '+' \
  |sed -r -e "s;(.*)[+]$;\1;" -e "s/.*/scale=2;(&)\/$nTimes/"`;
nPercCpu=`echo "$strCalc" |bc -l`
echo $nPercCpu

use like: calcPercCpu.sh 1234 where 1234 is the pid

For the specified $nPid, it will measure the average of 10 snapshots of the cpu usage in a whole of 1 second (delay of 0.1s each * nTimes=10); that provides a good and fast accurate result of what is happening in the very moment.

Tweak the variables to your needs.

Community
  • 1
  • 1