#!/usr/bin/env python

import sys
import os
import subprocess
from decimal import Decimal
from decimal import getcontext def cpu_proc(pid):
'''
Reference:https://stackoverflow.com/questions/16726779/how-do-i-get-the-total-cpu-usage-of-an-application-from-proc-pid-stat
:param pid:
:return:
'''
try:
with open(os.path.join('/proc/', pid, 'stat'), 'r') as pidfile:
proctimes = pidfile.readline()
# get utime from /proc/<pid>/stat, 14 item
utime = proctimes.split(' ')[13]
# get stime from proc/<pid>/stat, 15 item
stime = proctimes.split(' ')[14]
cutime = proctimes.split(' ')[15]
cstime = proctimes.split(' ')[16]
total_time =int(utime) + int(stime) + int(cutime) + int(cstime)
uptime = cput()
starttime = proctimes.split(' ')[21]
Hertz = subprocess.Popen("getconf CLK_TCK", shell=True,stdout=subprocess.PIPE).communicate()[0].strip('\n')
seconds =Decimal(str(uptime)) + Decimal(str(starttime)) +Decimal(str(Hertz))
getcontext().prec = 4
cpu_usag = Decimal('') * (( Decimal(str(total_time)) / Decimal(str(Hertz)) )/ Decimal(str(seconds)))
return cpu_usag
except IOError as e:
print('ERROR: %s' % e)
sys.exit(2) def cpu_top(pid):
try:
proc = subprocess.Popen("top -p %s -b -n 1 | grep -w ezk-agent | awk '{print $9}'" % pid, shell=True, stdout=subprocess.PIPE)
cpu_percentage = proc.communicate()
return cpu_percentage[0].rstrip('\n')
except KeyboardInterrupt:
sys.exit(0) def cput():
try:
with open('/proc/uptime', 'r') as procfile:
cputimes = procfile.readline()
return(float(cputimes.split(' ')[0]))
except IOError as e:
print('ERROR: %s' % e)
sys.exit(3) def mem_usage_calc(pid):
(memkb, err)= subprocess.Popen("pmap -x "+pid+"|grep -i total|awk '{print $3}'", shell=True,
stdout=subprocess.PIPE).communicate()
return memkb.strip('\n') def fd_usage_calc(pid):
(fd_lsof_num, err) = subprocess.Popen("lsof -n|grep " + pid + "| wc -l", shell=True,
stdout=subprocess.PIPE).communicate()
pro_command="ls /proc/"+pid+"/fd|wc -l"
(fd_proc_num, err) = subprocess.Popen(pro_command, shell=True,
stdout=subprocess.PIPE).communicate()
return fd_lsof_num.strip('\n'),fd_proc_num.strip('\n') def main(pid):
print("pid:{}".format(pid))
print("*"*14 + "CPU" + "*"*14)
print "proc_get_value:{}".format(cpu_proc(pid))
print "top_get_value:{}".format(cpu_top(pid)) print("*"*14 + "MEM" + "*"*14)
print "mem_get_value:{}kB".format(mem_usage_calc(pid)) print("*"*10 + "File_Handler" + "*"*10)
print "File_Handler_lsof_get_value:{}".format(fd_usage_calc(pid)[0])
print "File_Handler_fd_get_value:{}".format(fd_usage_calc(pid)[1]) if __name__ == '__main__':
if len(sys.argv) == 2:
pid = sys.argv[1]
else:
try:
(out, err) = subprocess.Popen("ps -ef|grep ezk-agent/ezk-agent|grep -v grep|awk '{print $2}'", shell=True,
stdout=subprocess.PIPE).communicate()
pid = out.strip('\n')
except:
print('No PID specified. Usage: %s <PID>' % os.path.basename(__file__))
sys.exit(1)
main(pid)

013_针对单个pid的cpu/内存/io的资源占用统计的更多相关文章

  1. centos8平台使用pidstat监控cpu/内存/io

    一,安装pidstat: 1,安装 [root@localhost yum.repos.d]# yum install sysstat 2,查看版本: [root@localhost ~]# pids ...

  2. python glances来监控linux服务器CPU 内存 IO使用

    什么是 Glances? Glances 是一个由 Python 编写,使用 psutil 库来从系统抓取信息的基于 curses 开发的跨平台命令行系统监视工具. 通过 Glances,我们可以监视 ...

  3. Linux 查看CPU、Memory等资源占用情况

    linux下获取占用CPU资源最多的10个进程,可以使用如下命令组合: ps aux|head -1;ps aux|grep -v PID|sort -rn -k +3|head linux下获取占用 ...

  4. winform,WPF 释放内存垃圾,减少资源占用方法

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]        public static extern boo ...

  5. Linux 性能监控之CPU&内存&I/O监控Shell脚本1

    Linux 性能监控之CPU&内存&I/O监控Shell脚本1   by:授客 QQ:1033553122   #!/bin/bash # 获取要监控的本地服务器IP地址 IP=`if ...

  6. zabbix的安装(一)监控os资源:内存,cpu,io,负载,带宽

    一.Linux下开源监控系统简单介绍1)cacti:存储数据能力强,报警性能差2)nagios:报警性能差,存储数据仅有简单的一段可以判断是否在合理范围内的数据长度,储存在内存中.比如,连续采样数据存 ...

  7. 统计和分析系统性能【IO CPU 内存】的工具集合

    统计和分析系统性能[IO CPU 内存]的工具集合 blktrace http://www.oschina.net/p/blktrace 获取磁盘写入的信息 root@demo:~/install/p ...

  8. VPS性能测试:CPU内存,硬盘IO读写,带宽速度,UnixBench和压力测试

    现在便宜的VPS主机越来越多了,一些美国的VPS主机甚至给出1美元一月的VPS,堪比虚拟主机还要便宜,巨大的价格优势吸引不少人购买和使用,而近些年来国内的主机商也开始意识到便宜的VPS对草根站长的诱惑 ...

  9. 如何使用 Docker 来限制 CPU、内存和 IO等资源?

    如何使用 Docker 来限制 CPU.内存和 IO等资源?http://www.sohu.com/a/165506573_609513

随机推荐

  1. equals方法和==的区别--用实例简单说明

    首先我们创建一个类 public class People { private String name; private String address; public String getName() ...

  2. Video/Audio禁止快进(退)

    首先接着上个随笔.上个随笔主要介绍了视频音频的相关操作.属性和方法.这里主要记录一个应用:禁止快进(快退同理). 思路:监听快进事件(此处是监听播放时间更新),利用一个缓存的时间和播放到的时间进行对比 ...

  3. SDL 开发实战(七): SDL 多线程与锁机制

    为什么要用多线程?在音视频领域主要是实现音视频同步.实现了音视频同步,我们的播放器就基本上合格了. 这里我们将讲解一下SDL的多线程与锁机制. 多线程的好处主要是能使程序更加充分利用硬件(主要是CPU ...

  4. markdown用法

    Markdown 语法的目标是成为一种适用于网络的书写语言.不在 Markdown 涵盖范围之内的标签,都可以直接在文档里面用 HTML 撰写.不需要额外标注,只要直接加标签就可以了. 一.常用部分 ...

  5. vue.js window.removeEventListener 移除

    vue项目中的小坑记录下,想要移除window的addEventListener,需要把后面的function挂在到this上,removeEventListener 和 addEventListen ...

  6. HTML5 input date属性引起的探索——My97DatePicker(日期选择插件)

    不得不说H5的input date属性真的好用,之前我写的http://www.cnblogs.com/tu-0718/p/6729274.html这篇博客里面也有提到,不过虽然移动端对H5的支持还是 ...

  7. 『Shell编程』学习记录(1)

    例1. $ cat ex1 date pwd cd .. $ bash ex1 # 运行,显示当前日期和当前目录,但没有执行返回上级目录,因为执行的时候终端会产生一个子shell(类似于C语言调用函数 ...

  8. python脚本简化jar操作命令

    本篇和大家分享的是使用python简化对jar包操作命令,封装成简短关键字或词,达到操作简便的目的.最近在回顾和构思shell脚本工具,后面一些文章应该会分享shell内容,希望大家继续关注. 获取磁 ...

  9. ABP框架连接Mysql数据库

    开始想用Abp框架来搭建公司的新项目,虽然一切还没有定数,但是兵马未动,粮草先行,我先尝试一下整个过程,才能够更好的去争取机会. 此次技术选型:Abp(Asp.Net core mvc)+mysql( ...

  10. springcloud~服务注册与发现Eureka的使用

    服务注册与发现是微服务里的概念,也是一个基本的组件,负责服务组件的认证,即实现『你是谁』的功能,在服务注册与发现里,存在两种模式,即服务端发现和客户端发现,咱们今天说的eureka属于客户端发现! 下 ...