获取进程CPU使用率的3种方法

一个进程的CPU使用率是进程性能的一个重要指标。通过CPU使用率可以获知当然进程繁忙程度,或者获取该进程CPU使用异常情况。下面我们介绍3种方法来获取进程的CPU使用率。

通过zabbix获取

从zabbix 3.0开始,zabbix提供了一个item来获取进程CPU使用率,item为:

proc.cpu.util[<name>,<user>,<type>,<cmdline>,<mode>,<zone>]

各参数介绍如下

name - process name (default is all processes)
user - user name (default is all users)
type - CPU utilisation type:
total (default), user, system
cmdline - filter by command line (it is a regular expression) 
mode - data gathering mode: avg1 (default), avg5, avg15 
zone - target zone: current (default), all. This parameter is supported only on Solaris platform. Since Zabbix 3.0.3 if agent has been compiled on Solaris without zone support but is running on a newer Solaris where zones are supported and <zone> parameter is default or current then the agent will return NOTSUPPORTED (the agent cannot limit results to only current zone). However, <zone> parameter value all is supported in this case.

使用示例:

Examples:
⇒ proc.cpu.util[,root] → CPU utilisation of all processes running under the “root” user
⇒ proc.cpu.util[zabbix_server,zabbix] → CPU utilisation of all zabbix_server processes running under the zabbix user

The returned value is based on single CPU core utilisation percentage. For example CPU utilisation of a process fully using two cores is 200%. 

来自:zabbix文档

使用top命令

top命令是可以很直观的查看所有进程的信息,如内存使用,CPU使用率等。下面是使用top命令获取进程当前CPU使用率。

pid="123970"
top -b -n 1 -p $pid  2>&1 | awk -v pid=$pid '{if ($1 == pid)print $9}'

从/proc/读取

从/proc/[pid]/stat获取该进程的cpu时间,从/proc/stat获取系统cpu总时间,等待1秒,重新获取两个cpu时间。然后((cpu_time2 – cpu_time1) / (total_time2 – total_time1)) * 100*cpu_core;其中cpu_time为进程cpu使用时间,total_time为系统cpu使用时间,cpu_core为cpu核心数,通过/proc/cpuinfo获取。代码如下:

pid=3456
cpu_core=$(grep -c processor /proc/cpuinfo)
total_time1=$(awk '{if ($1 == "cpu") {sum = $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9 + $10 + $11;print sum}}' /proc/stat)
cpu_time1=$(awk '{sum=$14 + $15;print sum}' /proc/$pid/stat)
sleep 1
total_time2=$(awk '{if ($1 == "cpu") {sum = $2 + $3 + $4 + $5 + $6 + $7 + $8 + $9 + $10 + $11;print sum}}' /proc/stat)
cpu_time2=$(awk '{sum=$14 + $15;print sum}' /proc/$pid/stat)
awk -v cpu_time1=$cpu_time1 -v total_time1=$total_time1 -v cpu_time2=$cpu_time2 -v total_time2=$total_time2 -v cpu_core=$cpu_core 'BEGIN{cpu=((cpu_time2 - cpu_time1) / (total_time2 - total_time1)) * 100*cpu_core;print cpu}'
发布于:2019-11-18 10:18:52