I want to calculate CPU usage % for a given program in Linux. Lets say I want to calculate how much amount of CPU is being used by oracle. When I do ps -elf | grep oracle
I get multiple process. How can I get the cumulative result.

- 310
- 1
- 4
- 17
1 Answers
You cannot do simple ps -ef|grep oracle
because -ef
will output full information of all processes, including the command path. If you have any path containing string oracle
(in this case), it will be selected, finally, it will make your calculation incorrect.
I would do with pgrep
and ps
to pick out the right processes you want, and list only CPU usage, finally do the sum:
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 containsoracle
; you can use-x
to do exact match, if you are sure what process name you want to search. This will output all pid in a csv format, like123,234
ps -fho '%C' -p '123,234'
will output only CPU usage for the given pids, without header, each usage percentage in a lineThe final awk script will sum the value up, and print. The output should look like
CPU Usage:xx.xx%

- 27,591
- 48
- 66
- 103

- 189,393
- 32
- 233
- 301