#!/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. 关于'selffilter' is not a registered tag library. Must be one of:

    报错代码: 'selffilter' is not a registered tag library. Must be one of: admin_list admin_modify admin_st ...

  2. odoo action方法

    二.动作按钮里面也可以由字段判断: def action_select_sale_order_line(self,cr,uid,ids,date_begin,date_end,context=None ...

  3. 聊聊Unity2018的LWRP和混合光照

    0x00 前言 在这篇文章中,我们选择了过去几周Unity官方社区交流群以及UUG社区群中比较有代表性的几个问题,总结在这里和大家进行分享.主要涵盖了** Scripting.Assetsbundle ...

  4. 又双叒叕换,微软这次换Edge了

    http://tech.sina.com.cn/it/2018-12-06/doc-ihmutuec6481129.shtml 其实两个月前跟一个微软的前同事聊天已经听说过微软要基于Chromiun来 ...

  5. 关于 Docker 镜像的操作,看完这篇就够啦 !(下)

    紧接着上篇<关于 Docker 镜像的操作,看完这篇就够啦 !(上)>,奉上下篇 !!! 镜像作为 Docker 三大核心概念中最重要的一个关键词,它有很多操作,是您想学习容器技术不得不掌 ...

  6. 《白帽子讲Web安全》- 学习笔记

    一.为何要了解Web安全 最近加入新公司后,公司的官网突然被Google标记为了不安全的诈骗网站,一时间我们信息技术部门成为了众矢之的,虽然老官网并不是我们开发的(因为开发老官网的前辈们全都跑路了). ...

  7. DotNetCore跨平台~组件化时代来了

    回到目录 进行dotnetcore之后,各种对象都是基于DI进行生产的,这就有了对象的生命周期一说,早在autofac里也有相关知识点,这与Microsoft.Extensions.Dependenc ...

  8. Python3+unitest自动化测试初探(上篇)

    目录 1.概念介绍 2.准备工作 3.一个简单的例子 4.test fixture 5.测试套 1.概念介绍 unit test:单元测试,可以简单粗暴地理解成用一段代码去测试另外一段代码.unitt ...

  9. OA发展史:由点到生态

    在当今无边界组织的商业背景下,企业与员工关系已经转化为联盟关系,以往通过工作场所.劳动合同等约束的形式已经逐步弱化,管理行为空前复杂,OA正是将一个个散点整合起来的看不见的手.那么,推动OA发展的核心 ...

  10. 表单数据验证方法(一)—— 使用validate.js实现表单数据验证

    摘要:使用validate.js在前端实现表单数据提交前的验证 好久没写博客了,真的是罪过,以后不能这样了,只学习不思考,学的都是白搭,希望在博客园能记录下自己学习的点滴,虽然记录的都是些浅显的技术, ...