Accessing CPU/RAM usage (like with Task Manager, but via API!)?

前端 未结 3 658
野的像风
野的像风 2021-01-21 08:43

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 tha

3条回答
  •  无人共我
    2021-01-21 09:25

    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.

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

    • 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.

    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
    

提交回复
热议问题