每个线程的CPU使用率

问题描述 投票:0回答:5

我需要获取每个进程线程的 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 如下所示:

 4942 teamcity  20   0 3288m 831m 3124 R 33.3 10.6  10303:37 java
32700 teamcity  20   0 3288m 831m 3124 S  5.9 10.6  18:49.99 java
 5824 teamcity  20   0 3288m 831m 3124 S  5.9 10.6   1:57.90 java
 4621 teamcity  20   0 3288m 831m 3124 S  3.0 10.6   1834:09 java
 4622 teamcity  20   0 3288m 831m 3124 S  2.6 10.6   1844:15 java

线程使用 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...

我在这里缺少什么?

python multithreading
5个回答
7
投票

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

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))

4
投票

获取CPU百分比(间隔=0.1)

返回一个浮点数,表示进程 CPU 利用率的百分比。

当时间间隔 > 0.0 时 将进程时间与系统 CPU 时间进行比较 时间间隔前后经过的时间(阻塞)。

当间隔为 0.0 或 None 时 将进程时间与上次调用以来经过的系统 CPU 时间进行比较,立即返回。在这种情况下,为了准确性,建议在调用之间至少间隔 0.1 秒调用此函数。

这听起来很像它会告诉你返回了多少

non-idle 所花费的 CPU 时间(即:每个系统 CPU 时间的进程 CPU 时间量),而顶部显示了与“真实”时间相关的过程。考虑到你的数字,这似乎很现实。 要获得 top 所示的值,只需将每个线程的 CPU 使用率乘以该线程运行的核心的 CPU 使用率就可以了。 psutil.cpu_percent

应该对此有所帮助。请注意,在相乘之前,您需要将百分比除以 100.0(以获得 0 到 1 之间的“百分比”)。


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

4
投票
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))

我对 Florent Thiery 和 Gabe 解决方案进行了改进,创建了一个小脚本,可用于监视任何进程的 CPU 使用情况(按线程)。

2
投票

python cpuusage.py

import psutil, sys, time, os def clear(): if os.name == "nt": _ = os.system("cls") else: _ = os.system("clear") def get_threads_cpu_percent(p, interval=0.1): total_percent = p.cpu_percent(interval) total_time = sum(p.cpu_times()) return [('%s %s %s' % (total_percent * ((t.system_time + t.user_time)/total_time), t.id, psutil.Process(t.id).name())) for t in p.threads()] try: sys.argv[1] except: sys.exit('Enter PID') proc = psutil.Process(int(sys.argv[1])) while True: clear() threads = get_threads_cpu_percent(proc) threads.sort(reverse=True) for line in threads: print(line) time.sleep(1)

这些其他答案有点误导,因为提供的解决方案与 

0
投票
输出不匹配。如果您想跟踪以类似于

top

 的方式显示的 CPU 使用情况,您必须运行一个循环来执行以下操作...
如果我在进程 
a

下有线程

b

 和线程 
P
# Log the initial total time of process P: 
```
proc = psutil.Process(<your pid>)
initial_total_time = sum(proc.cpu_times())
```

# log the initial time of each thread
```

initial_thread_times = {'a': {'system': None, 'user': None}}

for thread in proc.threads():

    initial_thread_times[psutil.Process(thread.id).name()]['system'] = thread.system_time

    initial_thread_times[psutil.Process(thread.id).name()]['user'] = thread.user_time
```

# Determine total percent cpu usage over an interval
`total_cpu_percent = proc.cpu_percent(interval = 0.1)`
# grab the new total amount of time the process has used the cpu
`final_total_time = sum(proc.cpu_times())`
# grab the new system and user times for each thread
```
final_thread_times = {'a': {'system': None, 'user': None}}
for thread in proc.threads():
    final_thread_times[psutil.Process(thread.id).name()]['system'] = thread.system_time
    final_thread_times[psutil.Process(thread.id).name()]['user'] = thread.user_time
```
# calculate how much cpu each thread used by...
```
total_time_thread_a_used_cpu_over_time_interval = ((final_thread_times['a']['system']-initial_thread_times['a']['system']) + (final_thread_times['a']['user']-initial_thread_times['a']['user']))
total_time_process_used_cpu_over_interval = final_total_time - initial_total_time

percent_of_cpu_usage_utilized_by_thread_a = total_cpu_percent*(total_time_thread_a_used_cpu_over_time_interval/total_time_process_used_cpu_over_interval)

And if you iterate over this process you can dynamically report and calculate this like top
    

© www.soinside.com 2019 - 2024. All rights reserved.