[英]Calculating CPU usage of a program in Linux
I want to calculate CPU usage % for a given program in Linux. 我想计算Linux中给定程序的CPU使用率。 Lets say I want to calculate how much amount of CPU is being used by oracle. 可以说我想计算oracle正在使用多少CPU。 When I do ps -elf | grep oracle
当我做ps -elf | grep oracle
ps -elf | grep oracle
I get multiple process. ps -elf | grep oracle
我得到多个进程。 How can I get the cumulative result. 如何获得累积结果。
You cannot do simple ps -ef|grep oracle
because -ef
will output full information of all processes, including the command path. 您无法执行简单的ps -ef|grep oracle
因为-ef
将输出所有进程的完整信息,包括命令路径。 If you have any path containing string oracle
(in this case), it will be selected, finally, it will make your calculation incorrect. 如果您有任何包含字符串oracle
路径(在这种情况下),它将被选择,最后,它将使您的计算不正确。
I would do with pgrep
and ps
to pick out the right processes you want, and list only CPU usage, finally do the sum: 我将使用pgrep
和ps
来选择所需的正确进程,并仅列出CPU使用率,最后得出总和:
ps -fho' %C' -p $(pgrep -d, oracle )|awk '{s+=($0+0)}END{printf "CPU Usage:%.2f%%",s}'
pgrep -d, oracle
will list out the processes whose name contains oracle
; pgrep -d, oracle
将列出名称包含oracle
的进程; you can use -x
to do exact match, if you are sure what process name you want to search. 如果您确定要搜索的进程名称,则可以使用-x
进行完全匹配。 This will output all pid in a csv format, like 123,234
这将以csv格式输出所有pid,例如123,234
ps -fho '%C' -p '123,234'
will output only CPU usage for the given pids, without header, each usage percentage in a line ps -fho '%C' -p '123,234'
将仅输出给定pid的CPU使用情况,不包含标题,每行中的每个使用百分比
The final awk script will sum the value up, and print. 最终的awk脚本将对值求和,然后打印。 The output should look like 输出应该看起来像
CPU Usage:xx.xx%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.