1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 树莓派4B监控CPU占用率 内存使用率 磁盘使用量以及CPU温度

树莓派4B监控CPU占用率 内存使用率 磁盘使用量以及CPU温度

时间:2022-05-02 23:17:57

相关推荐

树莓派4B监控CPU占用率 内存使用率 磁盘使用量以及CPU温度

树莓派可以作为一个小型电脑,但是它不能像windows一样使用任务管理器查看当前资源占用情况

一、使用指令查看当前资源状态

使用top指令

可以获取当前Cpu使用状态、RAM使用率等信息,但是只能查看,无法长时间运行时保存下来

使用free指令

可以获得Mem信息,但是是以byte为单位,需要转换单位

使用df指令

可以获得文件系统占用的详情

二、用Python语言获取资源状态并存储为txt文件

import osimport timeimport logging# Return CPU temperature as a character string def getCPUtemperature():res = os.popen( 'vcgencmd measure_temp' ).readline()return (res.replace( "temp=" ," ").replace(" 'C\t "," "))# Return RAM information (unit=kb) in a list # Index 0: total RAM # Index 1: used RAM # Index 2: free RAM def getRAMinfo():p = os.popen( 'free' )i = 0while 1 :i = i + 1line = p.readline()if i == 2 :return (line.split()[ 1 : 4 ])# Return % of CPU used by user as a character string def getCPUuse():return ( str (os.popen( "top -n1 | awk '/Cpu\(s\):/ {print $2}'" ).readline().strip()))# Return information about disk space as a list (unit included)# Index 0: total disk space# Index 1: used disk space# Index 2: remaining disk space # Index 3: percentage of disk used def getDiskSpace():p = os.popen( "df -h /" )i = 0while 1 :i = i + 1line = p.readline()if i == 2 :return (line.split()[ 1 : 5 ])def get_info():# CPU informatiomCPU_temp = getCPUtemperature()CPU_usage = getCPUuse()# RAM information# Output is in kb, here I convert it in Mb for readabilityRAM_stats = getRAMinfo()RAM_total = round ( int (RAM_stats[ 0 ]) / 1024 , 1 )RAM_used = round ( int (RAM_stats[ 1 ]) / 1024 , 1 )RAM_free = round ( int (RAM_stats[ 2 ]) / 1024 , 1 )# Disk informationDISK_stats = getDiskSpace()DISK_total = DISK_stats[0]DISK_used = DISK_stats[1]DISK_left = DISK_stats[2]DISK_perc = DISK_stats[3]logging.info("Local Time {timenow} \n""CPU Temperature ={CPU_temp}""CPU Use = {CPU_usage} %\n\n""RAM Total = {RAM_total} MB\n""RAM Used = {RAM_used} MB\n""RAM Free = {RAM_free} MB\n\n""DISK Total Space = {DISK_total}B\n""DISK Used Space = {DISK_used}B\n""DISK Left Space = {DISK_left}B\n""DISK Used Percentage = {DISK_perc}\n""".format(timenow = time.asctime(time.localtime(time.time())),CPU_temp = CPU_temp,CPU_usage = CPU_usage,RAM_total = str(RAM_total),RAM_used = str(RAM_used),RAM_free = str(RAM_free),DISK_total = str(DISK_total),DISK_used = str(DISK_used),DISK_left = str(DISK_left),DISK_perc = str(DISK_perc),))if __name__ == '__main__':# get infologger_file = os.path.join('log_source_info.txt')handlers = [logging.FileHandler(logger_file, mode='w'),logging.StreamHandler()]logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] ''- %(levelname)s: %(message)s',level=logging.INFO,handlers=handlers)# while(1):while(True):get_info()time.sleep(10) # Time interval for obtaining resources

获取的文件形式如下:

三、获得了各种资源状态记录的txt文件,但是统计起来十分麻烦,特别是对于长时间记录的情况。可使用Python对保存的txt文件进行操作,将数据保存到csv,以CPU use和RAM use为例:

import numpy as npaddr = "log_source_info"len_txt = len(open(addr + ".txt",'r').readlines())len_data = int(len_txt / 13)data = np.zeros([len_txt, 1]).astype(object)data_i = 0 with open(addr + addr_num + ".txt", "r") as f:for line in f.readlines():line = line.strip('\n')data[data_i] = linedata_i += 1# print(data)# CPU_Temp = np.zeros([len_data, 1]).astype(object)CPU_Use = np.zeros([len_data, 1]).astype(object)RAM_Total = 2976.6RAM_Used = np.zeros([len_data, 1]).astype(object)# CPU_Temp_cont = 0CPU_Use_cont = 0RAM_Used_cont = 0cont = 0for data_t in data:# print(data_t)temp = data_t[0].split(" ")# if cont == 1 :# CPU_Temp[CPU_Temp_cont] = float(temp[3])# CPU_Temp_cont += 1if cont == 2:# find some data missif temp[3] == '%':CPU_Use[CPU_Use_cont] = 0else :# print(temp[3])CPU_Use[CPU_Use_cont] = float(temp[3])CPU_Use_cont += 1elif cont == 5:RAM_Used[RAM_Used_cont] = float(temp[3]) / RAM_TotalRAM_Used_cont += 1# print(data)cont += 1cont %= 13with open(addr + addr_num + ".csv", "w") as fw :# fw.write("CPU_Temp" + "," + "CPU_Use" + "," + "RAM_Used" + "," + "\n")fw.write("CPU_Use" + "," + "RAM_Used" + "," + "\n")for i in range(len_data):# fw.write(str(CPU_Temp[i,0]) + "," + str(CPU_Use[i,0]) + "," + str(RAM_Used[i,0]) + "\n")fw.write(str(CPU_Use[i,0]) + "," + str(RAM_Used[i,0]) + "\n")

注意!!!如果需要对CPU温度进行获取到csv文件,需要对txt文件进行处理,使用查找->替换,将

'C

替换为:

'C # 也就是在所有的摄氏度前面加一个空格,因为摄氏度为字符无法获得数据格式

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。