#!/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. vue 基础知识

    1. v-if 的使用: 假如后端传过来的数据,1 表示 “已完成”, 0表示 “未完成”, 那么如何根据 1.0显示出对应的表示信息呢? <p><span v-if="d ...

  2. Shell中map的使用

    Shell中的map与array有很多的相似之处,array操作:https://www.cnblogs.com/qq931399960/p/10786111.html 一.在使用map时,需要先声明 ...

  3. 从壹开始前后端分离【 .NET Core2.0 +Vue2.0 】框架之十三 || DTOs 对象映射使用,项目部署Windows+Linux完整版

    更新 很多小伙伴在用 IIS 发布的时候,总是会有一些问题,文章下边 #autoid-6-0-0 我也简单的动图展示了,如何 publish 到 IIS 的过程,如果你能看懂,却发现自己的项目有问题的 ...

  4. Spring 进入Controller前参数校验

    在进入Controller前完成参数的校验,针对对象参数 分为两个验证方式 (1)直接使用已定义的校验方式 1.在需要进行校验的属性上增加校验类型注解 import java.util.Date; i ...

  5. dataframe行变换为列

    新建一个 dataFrame : val conf = new SparkConf().setAppName("TTyb").setMaster("local" ...

  6. 5.Flask-Migrate

    1.1.项目结构重构 (1)config.py DB_URI = "mysql+pymysql://root:123456@127.0.0.1:3306/flask_migrate?char ...

  7. java~集合的介绍和使用

    大叔转载,原文地址:http://www.700net.com/rewrite.php/read-4491.html 线性表,链表,哈希表是常用的数据结构,在进行Java开发时,JDK已经为我们提供了 ...

  8. FSLIB.NETWORK 简易使用指南

    1.介绍 FSLIB.NETWORK 是一款开源HTTP的高性能高易用性网络库,是对HttpWebRequest/HttpWebResponse的包装,目的是为了用起来更简单明了.设计的时候就为了提供 ...

  9. java爬虫系列目录

    1. java爬虫系列第一讲-爬虫入门(爬取动作片列表) 2. java爬虫系列第二讲-爬取最新动作电影<海王>迅雷下载地址 3. java爬虫系列第三讲-获取页面中绝对路径的各种方法 4 ...

  10. java开发注解总结笔记

    目录 1.最基础注解(spring-context包下的org.springframework.stereotype) 1.1.@Controller @Service @Repository @Co ...