Python获得CPU和内存使用情况
郝伟 2022/08/15 发布, 2021/02/25 编写
本示例演示了通过Python获得机器CPU和内存的使用情况,输出格式如下所示:
ID Time(s) Speed(MB/s) Memory(GB)
1 1.01 0.99 0.0139
2 1.01 0.99 0.0139
3 1.01 0.99 0.0139
dataformat: time, cpu_usage, mem_used, mem_free
1660524168, 7.1,16.08,15.63
1660524169, 4.3,16.10,15.61
1660524170, 4.3,16.07,15.64
1660524171, 11.9,16.07,15.64
1660524172, 3.6,16.07,15.65
#encoding=utf-8 ''' 日期:2021/02/27 作者:郝伟 描述:获得CPU和内存使用情况 ''' import time, os import psutil # 第三方库 pip install psutil def get_info(): ''' Get information of cpu and memeory return format: time,cpu_usage,mem_used,mem_free ''' cpu=psutil.cpu_percent() mem = psutil.virtual_memory() mem_used = mem.used / 1073741824 mem_free = mem.free / 1073741824 return '{0},{1:5.1f},{2:5.2f},{3:5.2f}'.format(t0, cpu, mem_used, mem_free) def get_filename(): return './logs/usage_{0}.txt'.format(time.strftime("%Y%m%d", time.localtime())) if not os.path.exists('./logs/'): os.system('md logs') print('ID\tTime(s)\tSpeed(MB/s)\tMemory(GB)') for i in range(3): t1=time.time() time.sleep(1) t2=time.time() t = t2 - t1 + 0.001 speed = 1 / t mem = psutil.Process(os.getpid()).memory_info().rss / 1024 ** 3 print(u'{0}\t{1:.2f}\t{2:.2f}\t{3:.4f}'.format(i + 1, t, speed, mem)) print('dataformat: time, cpu_usage, mem_used, mem_free') filename=get_filename() logfile=open(filename, 'w', encoding='utf-8') t0=int(time.time()) t1=int(time.time()) while True: while t0==t1: time.sleep(0.1) t1 = int(time.time()) t0=t1 info=get_info() logfile.write(info+'\n') print(info) if t0 % 3 == 0: # 每3秒将缓冲中的数据写到文件中一次 logfile.flush() # 每天一个日志文件,文件名格式为 usage_yyyyMMdd.txt,如 usage_20210227.txt if filename != get_filename(): filename=get_filename() logfile.close() logfile=open(filename, 'w', encoding='utf-8') logfile.close()