Rem*_*tec 4 python cpu cpu-usage python-2.7 raspberry-pi
试图在Python不使用PSUtil.
我已经尝试了以下但它似乎总是报告相同的数字......
def getCPUuse():
return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\
)))
print(getCPUuse())
Run Code Online (Sandbox Code Playgroud)
即使我加载 CPU,这似乎总是报告 3.7%。
我也尝试了以下...
str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2))
Run Code Online (Sandbox Code Playgroud)
这似乎总是返回 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
Run Code Online (Sandbox Code Playgroud)
我猜我的命令没有从上述输出中正确提取所有 CPU 内核的值?
我的目标是在不使用 PSUtil 的情况下从我的设备(Raspberry PI)获得总 CPU %。该图应反映操作系统任务管理器中显示的内容。
PSUtil、htop、mpstat 等所做的是读取以"cpu"(实际上是第一行) from开头的行/proc/stat,然后根据该行中的值计算百分比。您可以在man 5 proc(搜索“proc/stat”)中找到该行中值的含义。
这也是grep cpu /proc/stat | awk ....你提到的命令所做的。但是中的值/proc/stat代表自上次启动以来花费的时间!也许他们会在一段时间后回绕,我不确定,但关键是这些数字是在很长一段时间内测量的。
因此,如果您运行该命令,并在几秒钟(、几分钟甚至几小时)后再次运行它,它们将不会有太大变化!这就是为什么你看到它总是返回 5.12。
程序会top记住以前的值并从新读取的值中减去它们。根据结果,可以计算出实际反映最近 CPU 负载的“实时”百分比。
为了尽可能简单地在 python 中做类似的事情,但不运行外部命令来/proc/stat为我们读取和计算,我们可以将读取的值存储到文件中。下一次运行我们可以读回它们,并从新值中减去它们。
#!/usr/bin/env python2.7
import os.path
# Read first line from /proc/stat. It should start with "cpu"
# and contains times spent in various modes by all CPU's totalled.
#
with open("/proc/stat") as procfile:
cpustats = procfile.readline().split()
# Sanity check
#
if cpustats[0] != 'cpu':
raise ValueError("First line of /proc/stat not recognised")
#
# Refer to "man 5 proc" (search for /proc/stat) for information
# about which field means what.
#
# Here we do calculation as simple as possible:
# CPU% = 100 * time_doing_things / (time_doing_things + time_doing_nothing)
#
user_time = int(cpustats[1]) # time spent in user space
nice_time = int(cpustats[2]) # 'nice' time spent in user space
system_time = int(cpustats[3]) # time spent in kernel space
idle_time = int(cpustats[4]) # time spent idly
iowait_time = int(cpustats[5]) # time spent waiting is also doing nothing
time_doing_things = user_time + nice_time + system_time
time_doing_nothing = idle_time + iowait_time
# The times read from /proc/stat are total times, i.e. *all* times spent
# doing things and doing nothing since last boot.
#
# So to calculate meaningful CPU % we need to know how much these values
# have *changed*. So we store them in a file which we read next time the
# script is run.
#
previous_values_file = "/tmp/prev.cpu"
prev_time_doing_things = 0
prev_time_doing_nothing = 0
try:
with open(previous_values_file) as prev_file:
prev1, prev2 = prev_file.readline().split()
prev_time_doing_things = int(prev1)
prev_time_doing_nothing = int(prev2)
except IOError: # To prevent error/exception if file does not exist. We don't care.
pass
# Write the new values to the file to use next run
#
with open(previous_values_file, 'w') as prev_file:
prev_file.write("{} {}\n".format(time_doing_things, time_doing_nothing))
# Calculate difference, i.e: how much the number have changed
#
diff_time_doing_things = time_doing_things - prev_time_doing_things
diff_time_doing_nothing = time_doing_nothing - prev_time_doing_nothing
# Calculate a percentage of change since last run:
#
cpu_percentage = 100.0 * diff_time_doing_things/ (diff_time_doing_things + diff_time_doing_nothing)
# Finally, output the result
#
print "CPU", cpu_percentage, "%"
Run Code Online (Sandbox Code Playgroud)
这是一个与 不同的版本,它top每秒打印一次 CPU 使用率,记住以前在变量而不是文件中测量的 CPU 时间:
#!/usr/bin/env python2.7
import os.path
import time
def get_cpu_times():
# Read first line from /proc/stat. It should start with "cpu"
# and contains times spend in various modes by all CPU's totalled.
#
with open("/proc/stat") as procfile:
cpustats = procfile.readline().split()
# Sanity check
#
if cpustats[0] != 'cpu':
raise ValueError("First line of /proc/stat not recognised")
# Refer to "man 5 proc" (search for /proc/stat) for information
# about which field means what.
#
# Here we do calculation as simple as possible:
#
# CPU% = 100 * time-doing-things / (time_doing_things + time_doing_nothing)
#
user_time = int(cpustats[1]) # time spent in user space
nice_time = int(cpustats[2]) # 'nice' time spent in user space
system_time = int(cpustats[3]) # time spent in kernel space
idle_time = int(cpustats[4]) # time spent idly
iowait_time = int(cpustats[5]) # time spent waiting is also doing nothing
time_doing_things = user_time + nice_time + system_time
time_doing_nothing = idle_time + iowait_time
return time_doing_things, time_doing_nothing
def cpu_percentage_loop():
prev_time_doing_things = 0
prev_time_doing_nothing = 0
while True: # loop forever printing CPU usage percentage
time_doing_things, time_doing_nothing = get_cpu_times()
diff_time_doing_things = time_doing_things - prev_time_doing_things
diff_time_doing_nothing = time_doing_nothing - prev_time_doing_nothing
cpu_percentage = 100.0 * diff_time_doing_things/ (diff_time_doing_things + diff_time_doing_nothing)
# remember current values to subtract next iteration of the loop
#
prev_time_doing_things = time_doing_things
prev_time_doing_nothing = time_doing_nothing
# Output latest perccentage
#
print "CPU", cpu_percentage, "%"
# Loop delay
#
time.sleep(1)
if __name__ == "__main__":
cpu_percentage_loop()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3214 次 |
| 最近记录: |