python消耗cpu_【原创】用python写的一个监测本地进程CPU占用的程序

#coding=utf-8

import psutil

import sys

import time

try:

#输入需要监测的进程PID

PID = raw_input('ProcessPID: ')

def get_cpu_info():

reload(sys)

sys.setdefaultencoding('utf-8')

#将结果记录到本地文本

text = open('D:\\CPUresult.txt', 'w')

i = 0

#博主新手靠这样来现实循环

while i < 100000000000000:

i = i + 1

#找出本机CPU的逻辑核个数

cpucount = psutil.cpu_count(logical=True)

#传入进程PID,实现监测功能

process = psutil.Process(int(PID))

cpupercent = process.cpu_percent(interval=2)

#得到进程CPU占用,同资源检测管理器的数据

cpu = int(cpupercent / cpucount)

if cpu <= 50:

print u'CPU使用率:%s%%' % cpu + ' ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

print>> text, u'CPU使用率:%s%%' % cpu + ' ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

else:

print u'CPU使用率:%s%%,占用率过高' % cpu + ' ' + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

print>> text, u'CPU使用率:%s%%,占用率过高' % cpu + ' ' + time.strftime('%Y-%m-%d %H:%M:%S',

time.localtime())

text.close()

print u'进程%s的' % PID + u'cpu监控已经运行,结果将在D:\\result.txt生成'

time.sleep(1)

print "-------------------------------------------------"

print get_cpu_info()

finally:

print u'进程%s' % PID + u'已经结束'

raw_input()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值