psutil:测量特定进程的cpu使用率 [英] psutil: Measuring the cpu usage of a specific process

查看:1088
本文介绍了psutil:测量特定进程的cpu使用率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测量进程树的CPU使用率.

Im trying to measure the cpu usage of a process tree.

当前获得进程的cpu_usage(没有子进程)可以,但是我得到的结果很奇怪.

Currently getting the cpu_usage of a process (without children) will do, but I'm getting weird results.

import psutil
p = psutil.Process(PID)
p.cpu_percent

还给我> 100,那怎么可能呢?

gives me back float>100, how is that even possible?

btw PID是简单事物的pid

btw PID is the pid of something simple as

def foo():
    i = 0
    while True:
        i += 1

根据任务管理器,其cpu使用率约为12%

which according to task manager its cpu usage is around 12%

我想获得12.5或类似内容的输出.

I want to get an output of 12.5 or something like that.

推荐答案

我阅读了有关psutil的一些文档,这是我得到的:

I read some documentation about psutil and here is what I got:

注意:大于100的百分比是合法的,因为它可能是由多个线程在不同CPU内核上运行的进程导致的.

Note: a percentage > 100 is legitimate as it can result from a process with >multiple threads running on different CPU cores.

因此,要摆脱> 100,您应该执行以下操作:

So in order to get rid of >100 you should do something like this:

注意:返回值显然不是在所有CPU内核之间平均分配(与psutil.cpu_percent()不同).这意味着在具有2个CPU内核的系统上运行的繁忙循环进程将被报告为具有100%的CPU利用率,而不是50%的CPU利用率.这样做是为了与UNIX的"top"实用程序一致,并且还使识别占用CPU资源(独立于CPU内核数量)的进程更容易.必须注意,在上面的示例中,Windows上的taskmgr.exe将报告50%的使用率.要模拟Windows的taskmgr.exe行为,您可以执行以下操作:

Note: the returned value is explcitly not split evenly between all CPUs cores (differently from psutil.cpu_percent()). This means that a busy loop process running on a system with 2 CPU cores will be reported as having 100% CPU utilization instead of 50%. This was done in order to be consistent with UNIX’s "top" utility and also to make it easier to identify processes hogging CPU resources (independently from the number of CPU cores). It must be noted that in the example above taskmgr.exe on Windows will report 50% usage instead. To emulate Windows’s taskmgr.exe behavior you can do:

p.cpu_percent()/psutil.cpu_count().

p.cpu_percent() / psutil.cpu_count().

由于我从其他地方得到了这个答案,因此我将为您提供一个链接以进行检查 出: http://psutil.readthedocs.io/en/版本2.2.1/#psutil.Process.cpu_percent

Since i got this answer from somewhere else, I'll give you a link to check it out: http://psutil.readthedocs.io/en/release-2.2.1/#psutil.Process.cpu_percent

这篇关于psutil:测量特定进程的cpu使用率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆