LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How to get %CPU usage of a process (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-get-cpu-usage-of-a-process-63726/)

devershetty 06-04-2003 08:55 PM

How to get %CPU usage of a process
 
Hi there,

I need to get %CPU usage of process , I tried following method on Redhat 7.3 Linux 2.4.18-3
1. read /proc/<PID>/stat (utime) entry and save in val1
2. read same /proc/<PID>/stat (utime) entry after 5 seconds and store in val2
3. calculate by using (val2 - val1) / 500 (since jiffies is 1/100 of second).

Does this make any sense.
But when I look at command output of ps -auxw, %CPU usage is about 50-60%(for eg) for daemons (i.e., <PID> above method).
This is a different value than I calculated using above method.

Please let me know
1. if above method is not correct, let me know correct method to calculate %CPU usage of process.
2. Is there any IOCTL calls to process management in Linux where i can get automated value of %CPU usage.

Thanks in Advance.
-KOTRESH.D

belial 06-05-2003 06:25 AM

help
 
To wiev your usage of procesor use /sbin/top utility.
Or simply use ps
Or simply install Linux Slackware :-)

figadiablo 06-05-2003 06:40 AM

typing the "top" command should give you all of this information.

this is from the man pages:

NAME
top - show system usage statistics

SYNOPSIS
top [-u] [-w] [-k] [-s interval] [-e | -d | -a] [-l samples] [number]

DESCRIPTION
top displays an ongoing sample of system usage statistics. It operates
in various modes, but by default shows cpu utilization and memory usage
for each process in the system.

devershetty 06-06-2003 01:03 AM

Hello..
Thanks for your replies.

But I need to get the value of %CPU usage of process specified by PID programmatically
not from command line.
My above method is in reference to linux mailing lists and has drawbacks of sleeping for 5 seconds.
I have other idea for this using popen() and fread().
for eg command name --> xxx, its PID --> yyy.
FILE * fp;char buf[1024];
char * cmd =" ps -C xxx -o yyy=-eo\"%C %x %t %a\"";
fp = popen(cmd,"r");
fread(buf,1,sizeof(buf),fp);

Now buf has instant value of %CPU usage.Is this OK..
But I feel using command strings in application programs is not good practice.
Using API s or IOCTL is considered as good practice.
Is there any other idea??.

TIA.
Kotresh.

romydmisc 05-23-2006 10:12 PM

Hi Kotresh,

I'm also working on to find %CPU usage of a particular process. My problem is just a little more complex, i'm trying to find Peak CPU usage and average CPU usage of a particular process. I also want to do it programmatically and not from command line.

So did u ever figured out how to do it, if yes, could you share the solution with me.

Thanks,
Romy

haertig 05-23-2006 11:56 PM

The third column of the output below is the CPU utilization (expressed as a percent):
Code:

$ ps aux | grep " <pid> " | grep -v grep
Note: That was "ps aux", not "ps -aux". No dash in the options. The lack of a dash before the options indicates the BSD variation of the command.

Example: My X server, pid 5562, is currently using 1.2% of the CPU cycles (and 2.5% of memory - the fourth column - if you care about that):
Code:

$ ps aux | grep " 5562 " | grep -v grep
root      5562  1.2  2.5  32260 26144 ?        RL  16:49  4:26 /usr/X11R6/bin/X :0 -dpi 96 -audit 0 -auth /var/lib/gdm/:0.Xauth -nolisten tcp vt7
$

[edit]p.s. - It's better to start a new thread, than to dig up one as old as this. The original was from 2003, quite a long time ago![/edit]

ajucan 07-04-2006 08:00 AM

CPU Utilization - C program ?
 
Hello,
have you done something with C programming %CPU utilization?
I need to know how to do it, "top" source code is so big for me...

For the moment i'm using ps to get it, output it and parse it later to extract cpu and memory utilization, but ps is not so accurate as i hoped. I mean there are BIG differences between output of ps and top in cpu utilization...Don't know what to do.

Thanks and regards,

Andrei

Pravab 07-04-2006 09:58 AM

in FEDORACORE they have the option called "SYSTEM MONITER" : i dont acatly remember where though

ajucan 07-05-2006 07:59 AM

Quote:

Originally Posted by Pravab
in FEDORACORE they have the option called "SYSTEM MONITER" : i dont acatly remember where though

HI,
that's the problem, i need something that should run in the background on all UNIX platforms ( AIX, HPUX, Solaris, MacOSX and Linux ), at least one version of file ( script or c code ) for each of these platforms.

I have examples were ps -eo comm,pcpu | grep program_name is returning something like :
program_name 1 ( that means 1% CPU utilization, isn't so? )

and when top -b -n 1 | grep program_name it returns ~60% in CPU utilization.....

That's why i think ( looked over top3.5 source code ) that "top" is more accurate then "ps".
Please if somebody has an opinion ( with examples ofcourse :), post it!

Thanks and regards to all,
AJ

Pravab 07-06-2006 01:52 PM

Quote:

Originally Posted by Pravab
in FEDORACORE they have the option called "SYSTEM MONITER" : i dont acatly remember where though

In the panal, there is option called "System" and inside it in "Administration" there is option called System Monitor

_slap 09-23-2007 10:46 AM

script
 
Hi all.

I've writted a little script to control the cpu usage by a process.

Here's the code:
-----------------------------------------
Code:

#!/bin/bash
#
# Control de procesos
#
# El script controla que el <proceso> no consuma más cpu del <límite>
# Si se sobrepasa el límite el script mata el proceso y acaba.
#
# Para linux kernels 2.6.x
# v.0.1 sept-2007
#
# Autor: Miguel Ángel Molina Molina
# Licencia: GPL v.2

# Check de parámetros
# El parámetro debug es opcional y puede ser cualquier cosa. Si existe, se imprime salida por pantalla para depuración o pruebas
if [ $# -lt 2 -o $# -gt 3 ];
then
  echo "Uso: `basename $0` <proceso> <límite> [debug]"
  exit -1
fi

# existe debug?
if [ $# -eq 3 ];
then
  debug="si"
else
  debug=""
fi

procpid=`pidof $1`
typeset -i limite=$2

# Check de existencia del proceso
if [ -z "$procpid" ];
then
  echo "El proceso: $1 no existe"
  exit -1
fi

# Check del límite
if [ $limite -lt 1 -o $limite -gt 99 ];
then
  echo "Límite debe estar entre 1 y 99"
  exit -1
fi

typeset -i hits=0

while [ 1 ]
do
  # obtengo tiempo de utilización de cpu
  typeset -i cputime=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
  # check del pid del proceso
  if [ ! -f /proc/${procpid}/stat ];
  then
    echo "No existe el proceso: ${procpid}"
    exit -1
  fi
  # obtengo tiempo de uso de cpu por el proceso
  typeset -i proctime=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
  # espero 5 segundos
  sleep 5
  # vuelvo a obtener tiempo de utilización de cpu
  typeset -i cputime2=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
  # vuelvo a obtener tiempo de uso de cpu por el proceso
  typeset -i proctime2=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
  # calculo el porcentaje que supone el tiempo de uso de cpu del proceso respecto al tiempo total de cpu
  typeset -i cpu=$((($proctime2-$proctime)*100/($cputime2-$cputime)))
  [ ! -z $debug ] && echo "El proceso $1, con pid: $procpid, está consumiendo: $cpu% de cpu"
  # check de límite sobrepasado
  if [ $cpu -gt $limite ];
  then
    # cuento los sobrepasamientos
    let hits+=1
    if [ $hits = 1 ];
    then
      veces="vez"
    else
      veces="veces"
    fi
    [ ! -z $debug ] && echo "El proceso $1 ha sobrepasado el límite: $limite ($cpu) $hits $veces ..."
    # si ha superado los 10 sobrepasamientos, mato el proceso
    if [ $hits -gt 10 ];
    then
      echo -n "Matando proceso: $procpid ... "
      kill $procpid
      # espero a que el proceso muera
      sleep 1
      # check para comprobar si ha muerto el proceso
      if [ -z "`pidof $1`" ];
      then
        echo "Hecho."
      else
        echo "No se ha podido matar el proceso."
      fi
      echo "Finalizado."
      exit 0
    fi
  else
  # si no sobrepasa el límite, pongo a cero el contador
  let hits=0
  fi
done

-----------------------------------------

I hope it may be useful.
I would like to receive your comments.

P.S.: Sorry, I haven't translated it to english yet.

Regards.
_slap

_slap 12-27-2007 09:28 AM

script translation
 
Well, here's the translation to english.

Code:

#!/bin/bash
#
# Process control
#
# This shell-script watch that <process> doesn't pass the <limit> of % cpu usage
# If it does, the script kills that process and finish
#
# For linux kernel 2.6.x
# v.0.1 sept-2007
#
# Author: Miguel Ángel Molina Molina
# Licence: GPL v.2

# Parameter check
# [debug] parameter is optional and can be anything. If it exists, the script produces output to the screen for debugging purposes.
if [ $# -lt 2 -o $# -gt 3 ];
then
  echo "Usage: `basename $0` <process> <limit> [debug]"
  exit -1
fi

# [debug] exists?
if [ $# -eq 3 ];
then
  debug="yes"
else
  debug=""
fi

procpid=`pidof $1`
typeset -i limit=$2

# process existence check
if [ -z "$procpid" ];
then
  echo "Process: $1 doesn't exists"
  exit -1
fi

# limit check
if [ $limit -lt 1 -o $limit -gt 99 ];
then
  echo "Limit must be between 1 and 99"
  exit -1
fi

typeset -i hits=0

while [ 1 ]
do
  # Get usage cpu time
  typeset -i cputime=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
  # process pid check
  if [ ! -f /proc/${procpid}/stat ];
  then
    echo "Process doesn't exists: ${procpid}"
    exit -1
  fi
  # Get process usage cpu time
  typeset -i proctime=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
  # wait 5 seconds
  sleep 5
  # get usage cpu time, again
  typeset -i cputime2=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
  # get process usage cpu time, again
  typeset -i proctime2=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
  # calculate process usage cpu time over total usage cpu time as percentage
  typeset -i cpu=$((($proctime2-$proctime)*100/($cputime2-$cputime)))
  [ ! -z $debug ] && echo "Process $1, with pid: $procpid, is wasting: $cpu% of cpu"
  # limit exceed check
  if [ $cpu -gt $limit ];
  then
    # Count the excess
    let hits+=1
    if [ $hits = 1 ];
    then
      times="time"
    else
      times="times"
    fi
    [ ! -z $debug ] && echo "Process $1 has exceeded the limit: $limit ($cpu) $hits $times ..."
    # If hits are greater than 10, kill the process
    if [ $hits -gt 10 ];
    then
      echo -n "Killing process: $procpid ... "
      kill $procpid
      # wait until process die
      sleep 1
      # check if process has died
      if [ -z "`pidof $1`" ];
      then
        echo "Done."
      else
        echo "Can't kill the process."
      fi
      echo "Finished."
      exit 0
    fi
  else
  # if no limit exceed, reset hit counter
  let hits=0
  fi
done

Regards.

warrior_incredible 06-18-2008 12:48 AM

You all can use
top -p <processid1> -p <processid1>
to monitor specific processes ;)

Pravab 08-16-2008 11:51 AM

thanx guys for the help
:)


All times are GMT -5. The time now is 03:58 AM.