访问CPU/RAM的使用情况(与任务管理器一样,但通过API!)?

问题描述:

是否有使用Windows API访问任务管理器"信息的特定方法?我对此事做了相当多的搜索,但似乎找不到能够告诉我的API调用:

Is there a specific way to access "task manager" information with the Windows API? I have done a fair bit of searching on the matter, but I can't seem to find an API call that will tell me either:

  • 给定进程的CPU/RAM使用率
  • 使用最多CPU/RAM的进程

是否可以通过Python或C ++(基本上是通过Windows API)访问该信息?

Is there a way to access that information via Python or C++ (basically, via the Windows API)?

这实际上是我想要做的(用伪代码):

Here's what I'm essentially trying to do (in pseudo code):

app x = winapi.most_intensive_process
app y = winapi.most_RAM_usage

print x.name
print y.name

您可以直接使用 psutil 库,它是一个跨平台的库,提供了许多有关进程的信息.它可以在Windows,Linux,Mac OS,BSD和Sun Solaris上运行,并且可以以32位和64位方式与2.4到3.4的python一起使用.

Instead of calling the windows API directly you can use the psutil library which is a cross-platform library that provides a lot of information about processes. It works on Windows, Linux, Mac OS, BSD and Sun Solaris and works with python from 2.4 to 3.4 in both 32 and 64 bit fashion.

特别是 Process 类具有以下有趣的方法:

In particular it's Process class has the following interesting methods:

  • cpu_times :用户和系统计时所花费的时间从一开始就是这个过程.
  • cpu_percent :自上次以来的cpu利用率百分比通话或在给定的时间间隔内
  • memory_info :有关Ram和虚拟内存的信息用法.注意:文档明确指出,这些是 taskmgr.exe 所示的内容,因此看起来确实正是您想要的.
  • memory_info_ex :扩展的内存信息.
  • memory_percent :过程.
  • cpu_times: user and system timings spent by the process from its start.
  • cpu_percent: percentage of cpu utilization since last call or in the given interval
  • memory_info: info about Ram and virtual memory usage. NOTE: the documentation explicitly states that these are the one shown by taskmgr.exe so it looks like exactly what you want.
  • memory_info_ex: extended memory information.
  • memory_percent: percentage of used memory by the process.

要遍历所有进程(例如,查找最繁忙的CPU/内存),您可以遍历 process_iter .

To iterate over all processes (in order to find the most CPU/memory hungry for example), you can just iterate over process_iter.

这是您要实现的目标的简单实现:

Here's a simple implementation of what you wanted to achieve:

import psutil

def most_intensive_process():
    return max(psutil.process_iter(), key=lambda x: x.cpu_percent(0))

def most_RAM_usage():
    return max(psutil.process_iter(), key=lambda x: x.memory_info()[0])

x = most_intensive_process()
y = most_RAM_usage()

print(x.name)
print(y.name)

在我的系统上运行的示例:

Sample run on my system:

In [23]: def most_intensive_process():
    ...:     # psutil < 2.x has get_something style methods...
    ...:     return max(psutil.process_iter(), key=lambda x: x.get_cpu_percent(0))
    ...: 
    ...: def most_RAM_usage():
    ...:     return max(psutil.process_iter(), key=lambda x: x.get_memory_info()[0])

In [24]: x = most_intensive_process()
    ...: y = most_RAM_usage()
    ...: 

In [25]: print(x.name, y.name)
firefox firefox