Chinaunix首页 | 论坛 | 博客
  • 博客访问: 158881
  • 博文数量: 56
  • 博客积分: 2510
  • 博客等级: 少校
  • 技术积分: 502
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-18 14:21
文章分类

全部博文(56)

文章存档

2010年(39)

2009年(17)

我的朋友

分类: LINUX

2010-07-15 20:13:07


用shell脚本实现:

#!/bin/sh

pid=`ps -e|egrep "\b$1$" | awk '{print $1}'`#获取进程id
echo $pid
cpu=`top -n 1 -p $pid|tail -2|head -1|awk '{ssd=NF-4} {print $ssd}'`

#获取进程cpu占用

#echo $cpu

declare -i cpuall=0
declare -i time=0

while [ 1 ]
do
  cpu=`top -n 1 -p $pid|tail -2|head -1|awk '{ssd=NF-4} {print $ssd}'`
  cpuall=cpuall+cpu
  time=time+1
  average=`echo "scale=3;$cpuall/$time" |bc -l`
  #declare -i average=$cpuall/$time
  echo $average
  sleep 1
done


用法:
$./this.sh process


Python实现:

#!/usr/bin/python

import signal
import os
import sys
import re
import string
import time
import commands

exit = 0;

def getPID(ProcessName,PIDHash):
  pidstr = os.popen('ps -e').readlines();
  #print pidstr;
  PIDWatch = [];
  TmpRe = [];
  for p in ProcessName:
    TmpRe.append(re.compile('\s*([0-9]+).*(' + p + ')$'));
  for line in pidstr:
    #print line;
    for tmpre in TmpRe:
      result = tmpre.match(line);
      if result:
        PIDWatch.append(result.group(1));
        PIDHash[result.group(1)] = [result.group(1), result.group(2), 0.0, 0, 0.0, 0.0, 10000.0];
  return PIDWatch;

def getPIDCpuInfo(PIDWatch,PIDHash):
  if len(PIDWatch)==0:
    return;
  topcmd = [];
  for p in PIDWatch:
    topcmd.append('top -n 1 -p '+ p);
  while 1:
    flag = 0;
    print '-------------------------------------------';
    for cmd in topcmd:
      status,line = commands.getstatusoutput(cmd);
      #print line;
      line.strip();
      Info = line.split();
      #print Info;
      for p in PIDWatch:
        #print Info[-14], Info[-3], Info[-6], Info[-14];
        if len(Info) > 14 and PIDHash[p][0] in Info[-14] :
          flag = 1;
          PIDHash[p][2] += float(Info[-6]);
          PIDHash[p][3] += 1;
          PIDHash[p][4] = float(PIDHash[p][2])/float(PIDHash[p][3]);
          if float(Info[-6]) > float(PIDHash[p][5]):
             PIDHash[p][5] = float(Info[-6]);
          if float(Info[-6]) < float(PIDHash[p][6]):
             PIDHash[p][6] = float(Info[-6]);
          print "%-10s%-6s%.2f %.2f %.2f"%(PIDHash[p][0], PIDHash[p][1], PIDHash[p][4], PIDHash[p][5], PIDHash[p][6]);
    global exit;
    if flag == 0 or exit == 1:
      break;
    time.sleep(1);

def handler(signum, frame):
  global exit;
  exit = 1;

signal.signal(signal.SIGTERM,handler);
signal.signal(signal.SIGINT, handler);
signal.signal(signal.SIGALRM, handler);

if __name__ == "__main__":
  PIDHash = {};
  PIDWatch = getPID(sys.argv[1:],PIDHash);
  #print sys.argv[1:];
  #print PIDWatch;
  print 'PID Process AVERAGE MAX MIN';
  getPIDCpuInfo(PIDWatch,PIDHash);


用法:
$python this.py process1 process2
可以同时查看多个进程

输出(定时输 出):
PID   Process  AVERAGE
------------------------
3415  process1   0.0
3456  process2   1.2
阅读(1533) | 评论(0) | 转发(0) |
0

上一篇:自定义环形数组

下一篇:SDL教程源码

给主人留下些什么吧!~~