python查看cpu占用率

#! usr/bin/env python
#coding=utf-8
import time

import psutil

import warnings

from multiprocessing import cpu_count

cpu_max_percent = 90.0
div_mb = 1024.0**2
def check_CPU_state():
    check_ok = True
    cpu_used_percent = [0.0, 0.0, 0.0, 0.0]
    repeat = len(cpu_used_percent)
    print cpu_count()
    while repeat > 0:
        cpu_used_percent[repeat-1] = psutil.cpu_percent(1, 0)
        print cpu_used_percent
        time.sleep(1)
        repeat -= 1
    if sum(cpu_used_percent)/len(cpu_used_percent) >= cpu_max_percent:
        print "System CPU loading is too high ,almost ", sum(cpu_used_percent)/repeat
        check_ok = False
    else:
        check_ok = True
    return check_ok

if __name__ == "__main__":

    warnings.filterwarnings("ignore")
    print "[1] System CPU check! "
    if check_CPU_state():
        print "CPU loading check pass"
    else:
        print "CPU loading check fail"

附加:

import psutil
print psutil.cpu_count() #获取CPU逻辑个数
print psutil.cpu_count(logical=False) #获取CPU物理个数

你可能感兴趣的:(python查看cpu占用率)