正在尝试在Python
中获取CPU使用率而不使用PSUtil
。在
我试过下面的方法,但结果总是一样的。。。在
def getCPUuse():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\
)))
print(getCPUuse())
这似乎总是报告3.7%,即使当我加载CPU。在
我也试过以下几点。。。在
^{pr2}$这似乎总是返回5.12。我得承认我不知道上面说的是什么。如果我在命令行中输入grep cpu /proc/stat
,我会得到这样的结果。。。在
cpu 74429 1 19596 1704779 5567 0 284 0 0 0
cpu0 19596 0 4965 422508 1640 0 279 0 0 0
cpu1 18564 1 4793 427115 1420 0 1 0 0 0
cpu2 19020 0 4861 426916 1206 0 2 0 0 0
cpu3 17249 0 4977 428240 1301 0 2 0 0 0
我猜我的命令没有正确地从上面的输出中提取所有CPU核心的值?在
我的目标是在不使用PSUtil的情况下从我的设备(Raspberry PI)中获取总CPU%。该图应反映操作系统任务管理器中显示的内容。在
这并不容易,因为您描述的大多数进程都提供了CPU使用率的累积或总平均值。在
也许您可以尝试使用te
systat
包附带的mpstat
命令。在因此,我在以下脚本中使用的步骤是:
mpstat
生成两个报告,一个现在,另一个在1秒后(mpstat 1 2
)Average
行(最后一行)%idle
列,因此我们用awk
中的$NF
变量得到它Popen
,但是设置shell=True
来接受管道(|
)选项。在communicate()
)strip
清除输出因为它将休眠
1 second
,所以不要担心它不是一个即时命令。在PSUtil、htop、mpstat等都是从
/proc/stat
读取以"cpu"
开头的行(实际上是第一行),然后根据该行中的值计算一个百分比。您可以在man 5 proc
(搜索“proc/stat”)中找到该行中值的含义。在这也是您提到的
grep cpu /proc/stat | awk ....
命令的作用。但是/proc/stat
中的值代表自上次启动以来花费的时间!也许过了一段时间,我不确定,但关键是这些数据是经过很长时间测量的。在因此,如果您运行该命令,并在几秒钟(分钟甚至数小时)后再次运行它,它们不会有太大的变化!这就是为什么你看到它总是返回5.12。在
像
top
这样的程序会记住以前的值,并从新读取的值中减去它们。根据这个结果,可以计算出一个实际反映最近CPU负载的“实时”百分比。在为了尽可能简单地在python中执行类似的操作,但不运行外部命令来读取
/proc/stat
并为我们进行计算,我们可以将读取的值存储到一个文件中。下一次运行时,我们可以读回它们,并从新值中减去它们。在这是一个与
^{pr2}$top
不同的版本,它每秒打印CPU使用率,在变量中而不是在文件中记住先前测量的CPU时间:相关问题 更多 >
编程相关推荐