python吃内存还是cpu_Python2 得到 CPU 和内存信息要怎么实现呢?
Hakmor
2015-08-31 20:32:52 +08:00
@askfermi
@maemual
謝謝。附上寫好的代碼。
```python
#!/usr/bin/env python
import time
import psutil
line_num = 1
def print_line (str ):
print str
#function of Get CPU State
def getCPUstate (interval=1 ):
return (" CPU: " + str (psutil.cpu_percent (interval )) + "%")
#function of Get Memory
def getMemorystate ():
phymem = psutil.phymem_usage ()
buffers = getattr (psutil, 'phymem_buffers', lambda: 0 )()
cached = getattr (psutil, 'cached_phymem', lambda: 0 )()
used = phymem.total - (phymem.free + buffers + cached )
line = " Memory: %6s" % (
str (int (used / 1024 / 1024 )) + "M",
)
return line
def poll (interval ):
"""Retrieve raw stats within an interval window."""
# sleep some time
time.sleep (interval )
# get cpu state
cpu_state = getCPUstate (interval )
# get memory
memory_state = getMemorystate ()
return (cpu_state,memory_state )
def refresh_window (cpu_state,memory_state ):
#print current time #cpu state #memory
print_line (time.asctime ())
print_line (cpu_state )
print_line (memory_state )
try:
interval =0
while 1:
args = poll (interval )
refresh_window (*args )
interval = 1
except (KeyboardInterrupt, SystemExit ):
pass
```
總結
以上是生活随笔為你收集整理的python吃内存还是cpu_Python2 得到 CPU 和内存信息要怎么实现呢?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 接口测试多线程_pytho
- 下一篇: 三菱fx5u编程手册_实用分享 | 三菱