获取Linux上PHP任务消耗的CPU百分比


Getting CPU % consumed by a PHP task on Linux

如何使用PHP或bash获得Linux进程消耗的CPU百分比?我试图找到任何实用程序,但不能。

我在这里找到了这个惊人的答案:https://unix.stackexchange.com/questions/554/how-to-monitor-cpu-memory-usage-of-a-single-process

要在脚本中使用这些信息,可以这样做:

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

使用如下:calcperccpush .sh 1234其中1234是pid

对于指定的$nPid,它将在整个1秒内测量10个cpu使用快照的平均值(每个延迟0.1s * nTimes=10);这就提供了一个很好、很快速、很准确的结果,可以显示当前正在发生的事情。

根据需要调整变量