Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在不使用PSUtil的情况下获得python 2.7中的CPU使用率_Python_Python 2.7_Raspberry Pi_Cpu_Cpu Usage - Fatal编程技术网

如何在不使用PSUtil的情况下获得python 2.7中的CPU使用率

如何在不使用PSUtil的情况下获得python 2.7中的CPU使用率,python,python-2.7,raspberry-pi,cpu,cpu-usage,Python,Python 2.7,Raspberry Pi,Cpu,Cpu Usage,尝试在Python中获取CPU使用率,而不使用PSUtil 我试过以下方法,但它似乎总是报告相同的数字 def getCPUuse(): return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\ ))) print(getCPUuse()) 这似乎总是报告3.7%,即使我加载CPU 我也试过以下方法 str(round(float(os.popen('''grep 'cpu ' /

尝试在
Python
中获取CPU使用率,而不使用
PSUtil

我试过以下方法,但它似乎总是报告相同的数字

def getCPUuse():
    return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip(\
)))

print(getCPUuse())
这似乎总是报告3.7%,即使我加载CPU

我也试过以下方法

str(round(float(os.popen('''grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage }' ''').readline()),2))
这似乎总是返回5.12。我必须承认,我真的不知道上面所说的是什么。如果我在命令行中输入
grepcpu/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 12
  • 然后我们得到
    平均值
    行(最后一行)
  • 最后一列是
    %idle
    列,因此我们使用
    awk
  • 我们使用子流程中的
    Popen
    ,但设置
    shell=True
    接受管道(
    |
    )选项
  • 我们执行命令(
    communicate()
  • 条清洁输出
  • 从100中减去(空闲百分比),我们就可以得到使用的值
  • 由于它将休眠
    1秒
    ,因此不要担心它不是即时命令


    PSUtil、htop、mpstat等所做的是从
    /proc/stat
    读取以
    “cpu”
    开头的行(实际上是第一行),然后从该行中的值计算百分比。您可以在
    man 5 proc
    (搜索“proc/stat”)中找到该行上的值的含义

    这也是您提到的grepcpu/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, "%"
    
    这是一个与
    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()
    

    有趣的解决方案。您认为每个样品之间需要多少时间?我想知道是否可以将当前值保留在内存中,以避免写入文件,并在比较之前只休眠指定的时间。当然,top和htop就是这样做的:它们(默认情况下)每1秒刷新一次,并将以前在内存中花费的CPU时间保留1秒。“man 5 proc”表示时间是以秒为单位测量的“大多数体系结构上的1/100秒“。因此,只有当你开始使用短到,比如说,大大短于0.1秒的时间时,它们才开始变得不那么有意义。添加了一个版本的python脚本,该脚本不编写文件,但可以记住以前在变量中的度量值。出色的解决方案,+1我不知道这为什么没有获得足够的升级票!
    #!/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()