使用Python记录CPU内存使用率变化

2020-04-30  本文已影响0人  ljyfree

总体思路

运行Python脚本

$ cat resource_record.py 
#!/usr/bin/python
 
import psutil
import os,datetime,time

record_interval = 0.5 # unit is second

def getMemCpu():
    data = psutil.virtual_memory()
    total = data.total
    free = data.available
    memory = str(int(round(data.percent)))+"%"
    cpu = str(psutil.cpu_percent(interval=record_interval ))+"%"
    return (cpu,memory)

def main():
    now = time.strftime("%Y-%m-%d-%H_%M_%S",time.localtime(time.time()))
    fname = now+r"-report.csv"
    with open('%s' % fname,'w') as f:
        title_str = "Time, CPU ,Mem"
        print title_str
        f.write("Time, CPU ,Mem"+"\n")
        for i in xrange(999999):
            info = getMemCpu()
            tmp_str = "%4s,%5s,%4s" % (i*record_interval,info[0],info[1])
            print tmp_str
            f.write(tmp_str+"\n")

if __name__=="__main__":
    main()
~
$ python resource_record.py 
Time, CPU ,Mem
 0.0, 1.7%, 18%
 0.5, 0.8%, 18%
 1.0, 1.6%, 18%
 1.5, 1.3%, 18%
 2.0,25.4%, 18%
 2.5,23.7%, 18%
 3.0,25.2%, 18%
 3.5,23.8%, 18%
 4.0,24.3%, 18%
 4.5,23.3%, 18%
 5.0,25.3%, 18%
...
^CTraceback (most recent call last):
  File "resource_record.py", line 29, in <module>
    main()
  File "resource_record.py", line 23, in main
    time.sleep(record_interval)
KeyboardInterrupt
$ cat 2020-04-30-11_09_22-report.csv
Time, CPU ,Mem
 0.0, 1.7%, 18%
 0.5, 0.8%, 18%
 1.0, 1.6%, 18%
 1.5, 1.3%, 18%
...

绘图

上一篇下一篇

猜你喜欢

热点阅读