LinuxQuestions.org
Review your favorite Linux distribution.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!

Notices


Reply
  Search this Thread
Old 06-04-2003, 08:55 PM   #1
devershetty
LQ Newbie
 
Registered: Jun 2003
Location: Gangavathi, Karnataka(state), INDIA
Distribution: Redhat 7.3
Posts: 28

Rep: Reputation: 15
Question 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
 
Old 06-05-2003, 06:25 AM   #2
belial
LQ Newbie
 
Registered: May 2003
Distribution: GNU Linux Slackware
Posts: 18

Rep: Reputation: 0
Talking help

To wiev your usage of procesor use /sbin/top utility.
Or simply use ps
Or simply install Linux Slackware :-)
 
Old 06-05-2003, 06:40 AM   #3
figadiablo
Member
 
Registered: Feb 2002
Location: Virginia USA
Distribution: Slackware, CentOS, Fedora
Posts: 342

Rep: Reputation: 30
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.
 
Old 06-06-2003, 01:03 AM   #4
devershetty
LQ Newbie
 
Registered: Jun 2003
Location: Gangavathi, Karnataka(state), INDIA
Distribution: Redhat 7.3
Posts: 28

Original Poster
Rep: Reputation: 15
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.
 
Old 05-23-2006, 10:12 PM   #5
romydmisc
LQ Newbie
 
Registered: May 2006
Posts: 3

Rep: Reputation: 0
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
 
Old 05-23-2006, 11:56 PM   #6
haertig
Senior Member
 
Registered: Nov 2004
Distribution: Debian, Ubuntu, LinuxMint, Slackware, SysrescueCD, Raspbian, Arch
Posts: 2,331

Rep: Reputation: 357Reputation: 357Reputation: 357Reputation: 357
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]

Last edited by haertig; 05-23-2006 at 11:58 PM.
 
Old 07-04-2006, 08:00 AM   #7
ajucan
LQ Newbie
 
Registered: Jul 2006
Location: Bucharest, Romania
Distribution: Fedora Core 5
Posts: 2

Rep: Reputation: 0
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
 
Old 07-04-2006, 09:58 AM   #8
Pravab
Member
 
Registered: Apr 2006
Location: Dharan,Nepal
Distribution: FC5
Posts: 63

Rep: Reputation: 15
in FEDORACORE they have the option called "SYSTEM MONITER" : i dont acatly remember where though
 
Old 07-05-2006, 07:59 AM   #9
ajucan
LQ Newbie
 
Registered: Jul 2006
Location: Bucharest, Romania
Distribution: Fedora Core 5
Posts: 2

Rep: Reputation: 0
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
 
Old 07-06-2006, 01:52 PM   #10
Pravab
Member
 
Registered: Apr 2006
Location: Dharan,Nepal
Distribution: FC5
Posts: 63

Rep: Reputation: 15
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
 
Old 09-23-2007, 10:46 AM   #11
_slap
LQ Newbie
 
Registered: Sep 2007
Distribution: Ubuntu 7.04
Posts: 2

Rep: Reputation: 0
Lightbulb 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
 
Old 12-27-2007, 09:28 AM   #12
_slap
LQ Newbie
 
Registered: Sep 2007
Distribution: Ubuntu 7.04
Posts: 2

Rep: Reputation: 0
Smile 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.
 
Old 06-18-2008, 12:48 AM   #13
warrior_incredible
LQ Newbie
 
Registered: Jun 2008
Posts: 1

Rep: Reputation: 0
Smile

You all can use
top -p <processid1> -p <processid1>
to monitor specific processes
 
Old 08-16-2008, 11:51 AM   #14
Pravab
Member
 
Registered: Apr 2006
Location: Dharan,Nepal
Distribution: FC5
Posts: 63

Rep: Reputation: 15
thanx guys for the help
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
limit cpu % usage for a process student04 Linux - General 15 03-18-2014 07:22 PM
How to get %CPU usage of a process devershetty Linux - Newbie 1 08-18-2008 01:52 AM
process cpu usage vanv101 Fedora 9 06-24-2005 05:53 PM
Limiting a process CPU usage therandomthing Linux - Software 1 06-07-2005 09:00 PM
CPU usage of a process asharma Solaris / OpenSolaris 7 03-29-2003 02:17 PM

LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 03:02 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration