Linux获取指定进程CPU和内存占用率

Linux获取指定进程CPU和内存占用率

创建如下python程序,caclute_memory_occupied.py:

import psutil
import pynvml
import time

class MonitorProcess:
    def __init__(self,pid_num):
        self.pid = pid_num
        self.pro = psutil.Process(pid_num)
        self.pro_rss = 0.0
        self.pro_vss = 0.0
        self.pro_cpu = 0.0
        self.pro_io = 0.0
        self.pro_gpu = []
        try:
            pynvml.nvmlInit()
            self.deviceCount = pynvml.nvmlDeviceGetCount()
        except:
            print("No GPU")

    def Memonitor(self):
        self.pro_rss = float(self.pro.memory_info().rss)/1024/1024
        self.pro_vss = float(self.pro.memory_info().vms)/1024/1024

    def CPUMonitor(self):
        self.pro_cpu = self.pro.cpu_percent(interval = 1)

    def GPUMonitor(self):
        self.pro_gpu = []
        try:
            for gup_id in xrange(0,self.deviceCount):
                handle = pynvml.nvmlDeviceGetHandleByIndex(gpu_id)
                meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
                gpuratio_tmp = pynvml.nvmlDeviceGetUtilizationRates(handle)
                gpuratio = str(gpuratio_tmp.gpu) + " %"
                self.pro_gpu.append(gpuratio)
        except:
            pass
    def IoMonitor(self):
        self.pro_io = self.pro.io_counters()
    
    def GPUCount(self):
        return self.deviceCount
    
    def LastWork(self):
        list_return = []
        self.Memonitor()
        self.CPUMonitor()
        self.GPUMonitor()
        self.IoMonitor()
        list_return.append(self.pro_rss)
        list_return.append(self.pro_vss)
        list_return.append(self.pro_cpu)
        list_return.append(self.pro_gpu)
        return list_return

class CsvWrite:
    def __init__(self,csvname):
        self.f_out = open(csvname+".csv",'ab+')
        self.csv_write = csv.writer(self.f_out,dialect="excel")
    def CSVDataWrite(self,inlist):
        self.csv_write.writerow(inlist)
    def ClsoeCSV(self):
        self.f_out.close()

class TimeFuc:
    def __init__(self):
        pass
    def LocalTime(self):
        return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())

a = MonitorProcess(11718)
while 1:
    print(a.LastWork())

运行top指令,查看你关注的程序所占用的进程号:

$ top

修改caclute_memory_occupied.py中pid号,如下:

a = MonitorProcess(11718)

运行即可:

python caclute_memory_occupied.py
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值