简体   繁体   English

psutil:测量特定进程的cpu使用情况

[英]psutil: Measuring the cpu usage of a specific process

Im trying to measure the cpu usage of a process tree. 我试图测量进程树的CPU使用率。

Currently getting the cpu_usage of a process (without children) will do, but I'm getting weird results. 目前获取进程的cpu_usage(没有子进程)会有,但我得到了奇怪的结果。

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

gives me back float > 100 , how is that even possible? 让我回到float > 100 ,这怎么可能?

btw PID is the pid of something simple as 顺便说一下, PID是一个简单的pid

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

which according to task manager its cpu usage is around 12% 据任务经理说,它的CPU使用率约为12%

I want to get an output of 12.5 or something like that. 我想获得12.5或类似的输出。

I read some documentation about psutil and here is what I got: 我读了一些关于psutil的文档,这是我得到的:

Note: a percentage > 100 is legitimate as it can result from a process with >multiple threads running on different CPU cores. 注意:百分比> 100是合法的,因为它可能来自在多个CPU核心上运行多个线程的进程。

So in order to get rid of >100 you should do something like this: 所以为了摆脱> 100你应该做这样的事情:

Note: the returned value is explcitly not split evenly between all CPUs cores (differently from psutil.cpu_percent()). 注意:返回的值在所有CPU核心之间均匀分配(与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%. 这意味着在具有2个CPU内核的系统上运行的繁忙循环进程将报告为具有100%CPU利用率而不是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). 这样做是为了与UNIX的“顶级”实用程序保持一致,并且更容易识别占用CPU资源的进程(独立于CPU核心数)。 It must be noted that in the example above taskmgr.exe on Windows will report 50% usage instead. 必须注意的是,在上面的示例中,Windows上的taskmgr.exe将报告50%的使用率。 To emulate Windows's taskmgr.exe behavior you can do: 要模拟Windows的taskmgr.exe行为,您可以执行以下操作:

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

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 由于我从其他地方得到了这个答案,我会给你一个链接来检查它: http//psutil.readthedocs.io/en/release-2.2.1/#psutil.Process.cpu_percent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM