每个线程的CPU使用率

2024-05-14 19:02:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要得到每个进程线程的CPU%。在

所以,我创建了一个简单的脚本:

import psutil
from psutil import Process
p = psutil.Process(4499)

treads_list = p.get_threads()

for i in treads_list:
    o = i[0]
    th = psutil.Process(o)
    cpu_perc = th.get_cpu_percent(interval=1)
    print('PID %s use %% CPU = %s' % (o, cpu_perc))

下面是TOP在这个过程中的样子:

^{pr2}$

线程使用2.6-5.9%的CPU,父PID使用33.3。在

但是-以下是脚本的结果:

# ./psutil_threads.py
PID 10231 use % CPU = 60.9
PID 10681 use % CPU = 75.3
PID 11371 use % CPU = 69.9
PID 11860 use % CPU = 85.9
PID 12977 use % CPU = 56.0
PID 14114 use % CPU = 88.8

看起来每个线程都“吃掉”了56-88%的CPU。。。在

我错过了什么?在


Tags: import脚本getusecpu线程processpid
3条回答

这将为您提供所需内容并匹配top(适应您的用例):

import psutil

def get_threads_cpu_percent(p, interval=0.1):
   total_percent = p.get_cpu_percent(interval)
   total_time = sum(p.cpu_times())
   return [total_percent * ((t.system_time + t.user_time)/total_time) for t in p.get_threads()]

# Example usage for process with process id 8008:
proc = psutil.Process(8008)
print(get_threads_cpu_percent(proc))

get_cpu_percent(interval=0.1)

Return a float representing the process CPU utilization as a percentage.

When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking).

When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls.

这听起来很像是返回了花在非空闲上的CPU时间(即:每个系统CPU时间的进程CPU时间量),而top显示的是进程相对于实际时间的CPU时间量。考虑到你的数字,这似乎很现实。在

要获得top将显示的值,只需将每个线程的CPU使用率乘以线程运行的内核的CPU使用率就可以了。psutil.cpu_percent应该有帮助。请注意,在乘以百分比之前,您需要将百分比除以100.0(以获得介于0和1之间的“百分比”)。在

虽然Gabe的回答很好,但请注意,较新的psutil版本需要以下更新的语法:

import psutil

def get_threads_cpu_percent(p, interval=0.1):
   total_percent = p.cpu_percent(interval)
   total_time = sum(p.cpu_times())
   return [total_percent * ((t.system_time + t.user_time)/total_time) for t in p.threads()]

# Example usage for process with process id 8008:
proc = psutil.Process(8008)
print(get_threads_cpu_percent(proc))

相关问题 更多 >

    热门问题