#!/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. kettle 备注

    1. 基本组成 1.1 spoon: 一个可视化的工具,用于编辑kettle ETL的任务脚本 1.2 span: 用以命令行方式执行spoon的转换 1.3 kitchen: 用以命令行方式执行sp ...

  2. javascript中apply、call和bind的区别及方法详解

    文章目录   apply.call apply.call 区别 apply.call实例 数组之间追加 获取数组中的最大值和最小值 验证是否是数组(前提是toString()方法没有被重写过) 类(伪 ...

  3. qml demo分析(samegame-拼图游戏)

    一.效果展示 相信大家都玩儿过连连看游戏,而且此款游戏也是闲时一款打发时间的趣事,那么接下来我将分析一款类似的游戏,完全使用qml编写界面,复杂逻辑使用js完成.由于此游戏包含4种游戏模式,因此本篇文 ...

  4. 【反编译系列】二、反编译代码(jeb)

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 概述 一般情况下我们都是使用dex2jar + jd-gui的方式反编译代码,在实际使用过程中,有时候发现反编译出来的代码阅读效果不是很好 ...

  5. ConfirmCancelUtilDialog【确认取消对话框封装类】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 对确认取消对话框的封装. 前提:调用对话框的Activity必须继承FragmentActivity及其子类(比如AppCompat ...

  6. 搞懂MySQL InnoDB事务ACID实现原理

    前言 说到数据库事务,想到的就是要么都做修改,要么都不做.或者是ACID的概念.其实事务的本质就是锁和并发和重做日志的结合体.那么,这一篇主要讲一下InnoDB中的事务到底是如何实现ACID的. 原子 ...

  7. OpenCV+TensorFlow实现自定义手写图像识别

    完整版请点击链接:https://mp.weixin.qq.com/s/5gHXGmLbtO7m3dOFrDUiHQ    或微信关注“大数据技术宅” 继用TensorFlow教你做手写字识别(准确率 ...

  8. 整合 MyPerf4J 做Java性能监控和统计工具

    快速启动MyPerf4J MyPerf4J 采用 JavaAgent 配置方式,透明化接入应用,对应用代码完全没有侵入. 打包 项目地址: https://github.com/LinShunKang ...

  9. ABAP案例:灵活读取SAP各表的数据

    案例说明     RFC读取表中数据. Import 参数名称 Type spec. 参考打印 FIELDS_NAME1 TYPE CHAR25 TABLE_NAME1 TYPE CHAR25 WHE ...

  10. C# 绘制PDF嵌套表格

    嵌套表格,即在一张表格中的特定单元格中再插入一个或者多个表格,使用嵌套表格的优点在于能够让内容的布局更加合理,同时也方便程序套用.下面的示例中,将介绍如何通过C#编程来演示如何插入嵌套表格到PDF文档 ...