如何在 python 中获得 CPU 利用率?
How to get CPU utilisation in python?
目前我使用 psutil
获取 RAM 百分比
print (' ')
print ('----------------------CPU Information summary----------------------')
print (' ')
# gives a single float value
vcc=psutil.cpu_count()
print ('Total number of CPUs :',vcc)
vcpu=psutil.cpu_percent()
print ('Total CPUs utilized percentage :',vcpu,'%')
但是当我 运行 我得到这个代码时
----------------------CPU Information summary----------------------
Total number of CPUs : 8
Total CPUs utilized percentage : 0.0 %
但我希望它在任务管理器中打印 CPU %
如文档中所述:
psutil.cpu_percent(间隔=None, percpu=False)
Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case it is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.
所以它需要在调用之间有一个间隔来调用它,这样它才能给出正确的百分比。
这样调用它(或尝试使用间隔参数):
psutil.cpu_percent(interval=2)
目前我使用 psutil
获取 RAM 百分比
print (' ')
print ('----------------------CPU Information summary----------------------')
print (' ')
# gives a single float value
vcc=psutil.cpu_count()
print ('Total number of CPUs :',vcc)
vcpu=psutil.cpu_percent()
print ('Total CPUs utilized percentage :',vcpu,'%')
但是当我 运行 我得到这个代码时
----------------------CPU Information summary----------------------
Total number of CPUs : 8
Total CPUs utilized percentage : 0.0 %
但我希望它在任务管理器中打印 CPU %
如文档中所述:
psutil.cpu_percent(间隔=None, percpu=False)
Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case it is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.
所以它需要在调用之间有一个间隔来调用它,这样它才能给出正确的百分比。
这样调用它(或尝试使用间隔参数):
psutil.cpu_percent(interval=2)