0

tried with top command

top | grep <process name>

but the cpu percent changes ferequently .Moreover, if I compare the value with a monitoring tool which refreshes every five minutes it differs from it

tried with

ps -o %cpu -p <pid>

..but still no help

James Z
  • 12,209
  • 10
  • 24
  • 44
kanchan
  • 1
  • 4
  • ps -o %cpu shows the cpu usage for the lifetime of the process. Your monitoring tool might just show the CPU usage averaged over 5 minutes - you should figure out how your particular monitoring tool works. You can slow down top to average e.g. every 10 seconds by running top -d 10 , or 5 minutes by doing `top -d 300`. Since the CPU usage of the last 10 seconds or last 5 minutes are not stored anywhere, you'll have to wait 10 seconds or 5 minutes for the initial proper value. – nos Jun 20 '17 at 12:23

1 Answers1

-1

This is already answered in: https://stackoverflow.com/a/16736599/4004007

Preparation

To calculate CPU usage for a specific process you'll need the following:

  1. /proc/uptime
    • #1 uptime of the system (seconds)
  2. /proc/[PID]/stat
    • #14 utime - CPU time spent in user code, measured in clock ticks
    • #15 stime - CPU time spent in kernel code, measured in clock ticks
    • #16 cutime - Waited-for children's CPU time spent in user code (in clock ticks)
    • #17 cstime - Waited-for children's CPU time spent in kernel code (in clock ticks)
    • #22 starttime - Time when the process started, measured in clock ticks
  3. Hertz (number of clock ticks per second) of your system.

Calculation

First we determine the total time spent for the process:

total_time = utime + stime
 We also have to decide whether we want to include the time from children processes. If we do, then we add those values to

total_time:

total_time = total_time + cutime + cstime

Next we get the total elapsed time in seconds since the process started:

seconds = uptime - (starttime / Hertz)

Finally we calculate the CPU usage percentage:

cpu_usage = 100 * ((total_time / Hertz) / seconds)

See also

Top and ps not showing the same cpu result

How to get total cpu usage in Linux (c++)

Calculating CPU usage of a process in Linux

Nemanja Trifunovic
  • 3,017
  • 1
  • 17
  • 20