'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
>>文件: cpu使用率.py
>>作者: liu yang
>>邮箱: [email protected] ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #!/usr/bin/env python
# -*- coding: utf-8 -*- import psutil
from time import sleep def cpu_utilization(): cpu_start_alltime=psutil.cpu_times()
'''print(cpu_start_alltime)得到的内容:scputimes(user=14088.359375, system=20540.59375,
idle=362071.6875, interrupt=847.9375019073486, dpc=3795.6875)'''
t1all=sum(cpu_start_alltime)#开始的cpu时间总和 sleep(1)#休眠一秒 cpu_end_alltime=psutil.cpu_times()
t2all=sum(cpu_end_alltime)#结束时的cpu时间总和 t1busy=t1all-cpu_start_alltime.idle#开始的忙碌时间=总时间-空闲时间
t2busy=t2all-cpu_end_alltime.idle '''cpu使用率:(结束的忙碌时间-开始的忙碌时间)/(结束的总时间-开始的总时间)'''
cpu_busy=(t2busy-t1busy)/(t2all-t1all)*100
# print("cpu使用率:%0.2f"%cpu_busy+'%')
return cpu_busy if __name__ == '__main__':
cpu_used=cpu_utilization()
print("cpu使用率:%0.2f"%cpu_used+'%')#将得到的使用率一两位小数格式显示
05-04 01:22