检测系统的CPU、内存使用

一、windows系统

检测系统的CPU、内存使用_第1张图片

#coding:utf-8
# 先下载psutil库:pip install psutil
import psutil
import os, datetime, time

def getMemCpu():
    data = psutil.virtual_memory()
    total = data.total  # 总内存,单位为byte
    free = data.available  # 可以内存
    memory = "Memory usage:%d" % (int(round(data.percent))) + "%" + " "
    cpu = "CPU:%0.2f" % psutil.cpu_percent(interval=1) + "%"
    return memory + cpu

def main():
    while (True):
        info = getMemCpu()
        time.sleep(0.2)
        print(info)            #Memory usage:65% CPU:17.00%

if __name__ == "__main__":
    main()

 

二、linux系统

2.1、使用top查询

[root@testzq]# top
top - 22:03:22 up 12 days, 10:13,  2 users,  load average: 0.23, 0.23, 0.25
Tasks: 178 total,   1 running, 177 sleeping,   0 stopped,   0 zombie
%Cpu(s):  8.8 us,  0.3 sy,  0.0 ni, 91.4 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
KiB Mem : 16268356 total,  2715284 free,  6874236 used,  6678836 buff/cache
KiB Swap:  8388604 total,  8369176 free,    19428 used.  8640692 avail Mem

PID   USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
1733  mysql     20   0 2646916 442212   8356 S  27.7  2.7   3696:03 mysqld
7230  ctdi      20   0  752312  67788   5376 S   0.7  0.4   1:12.49 python

2.2、计算某段程序代码所消耗的CPU、内存大小

# -*- coding: utf-8 -*-
import os
import re
import time
from diserver.IOC_ENGINE.operate_engine import Engine

def get_cpu_mem_info():
    #获取CPU占用比信息
    cpustr = os.popen('top -bi -n 1').read().split('\n')[2]             #第三行:%Cpu(s):  8.0 us,  0.5 sy,  0.0 ni, 91.4 id,  0.0 wa,  0.0 hi,  0.1 si,  0.0 st
    cpudata = re.findall(r'-?\d+\.?\d*e?-?\d*?',cpustr)                 #['8.0', '0.5', '0.0', '91.4', '0.0', '0.0', '0.1', '0.0']
    cpupercent = '%.5f' %(100 - eval(cpudata[3]))
   
    # 获取内存信息
    memstr = os.popen("free").read().split('\n')[1]                    #'Mem:       16266796     5770032     9354084       18168     1142680    10147096'
    memdata = re.findall(r"\d+", memstr)                               #['16266796', '5770032', '9354084', '18168', '1142680', '10147096']
    mempercent = '%.5f' % (100 * (float(memdata[1]) / float(memdata[0])))
    return {"cpupercent": cpupercent,"mempercent":mempercent,"memtotal":memdata[0],"memused":memdata[1],"memfree":memdata[2]}



all_cpu_mem_file = 'all_cpu_mem.csv'         #配置日志路径和名字
allinitdata = 'processid,cpu%,mem%,memtotal,memused,memfree,time'                            #文件头信息
delta_cpu_mem_file = 'delta_cpu_mem.csv'
deltainitdata = 'processid,delta_cpu%,delta_mem%,delta_memused,time'


#获取当前的cpu、内存信息写入文件
def current_cpu_mem(pid,cpu_mem_info):
    cpupercent = cpu_mem_info["cpupercent"]
    mempercent = cpu_mem_info["mempercent"]
    memtotal = cpu_mem_info["memtotal"]
    memused = cpu_mem_info["memused"]
    memfree = cpu_mem_info["memfree"]
    currenttime = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
    if not os.path.exists(all_cpu_mem_file):
        with open(all_cpu_mem_file, 'w') as f:
            f.write(allinitdata)
            f.write('\n')
    wdata = str(pid)+','+cpupercent+','+mempercent+','+memtotal+','+memused+','+memfree+','+currenttime
    with open(all_cpu_mem_file, 'a+') as f:
        f.write(wdata)
        f.write('\n')


#获取一段程序间所消耗的cpu与内存资源
def delta_cpu_mem(pid,begine_cpu_mem,end_cpu_mem):
    delta_cpupercent = float(begine_cpu_mem["cpupercent"]) - float(end_cpu_mem["cpupercent"])
    delta_mempercent = float(begine_cpu_mem["mempercent"]) - float(end_cpu_mem["mempercent"])
    delta_memused = float(end_cpu_mem["memused"]) - float(begine_cpu_mem["memused"])
    currenttime = time.strftime("%Y-%m-%d-%H:%M:%S", time.localtime())
    if not os.path.exists(delta_cpu_mem_file):
        with open(delta_cpu_mem_file, 'w') as f:
            f.write(deltainitdata)
            f.write('\n')
    wdata = str(pid)+','+str(delta_cpupercent)+','+str(delta_mempercent)+','+str(delta_memused)+','+currenttime
    with open(delta_cpu_mem_file, 'a+') as f:
        f.write(wdata)
        f.write('\n')


#测试代码
def test_engine():
    begine_cpu_mem = get_cpu_mem_info()
    current_cpu_mem(os.getpid(), begine_cpu_mem)
    Engine()
    end_cpu_mem = get_cpu_mem_info()
    current_cpu_mem(os.getpid(), end_cpu_mem)
    delta_cpu_mem(os.getpid(), begine_cpu_mem, end_cpu_mem)

if __name__ == '__main__':
    test_engine()

 

你可能感兴趣的:(python,linux,CPU,内存,性能)