简体   繁体   English

如何使用 python 获得准确的进程 CPU 和 memory 使用情况?

[英]How to get accurate process CPU and memory usage with python?

I am trying to create a process monitor but I am unable to get accurate results comparing my results to windows task manager.我正在尝试创建一个过程监视器,但将我的结果与 windows 任务管理器进行比较,我无法获得准确的结果。

I have been using psutil which seems to work fine when looking at the overall cpu and memory usage but doesn't appear to be very accurate for a single process.我一直在使用 psutil,它在查看整体 cpu 和 memory 使用情况时似乎工作正常,但对于单个进程来说似乎不是很准确。 Memory usage is always higher than task manager and CPU it always random. Memory 使用率总是高于任务管理器和 CPU 它总是随机的。

I am setting the process once on initialise with self.process = psutil.Process(self.pid) and then calling the below method once a second, the process in task manager is running at a constant 5.4% cpu usage and 130mb ram however the below code produces:我使用self.process = psutil.Process(self.pid)在初始化时设置一次进程,然后每秒调用一次以下方法,任务管理器中的进程以恒定的 5.4% cpu 使用率和 130mb ram 运行,但是下面的代码产生:

CPU: 12.5375
Memory 156459008
CPU: 0.0
Memory 156459008
CPU: 0.0
Memory 156459008
CPU: 0.0
Memory 156459008
CPU: 12.5375
Memory 156459008
CPU: 0.0
Memory 156459008
CPU: 0.0
Memory 156459008

Example code:示例代码:

def process_info(self):    
        # I am calling this method twice because I read the first time gets ignored?
        ignore_cpu = self.process.cpu_percent(interval=None) / psutil.cpu_count()
        time.sleep(0.1)
        process_cpu = self.process.cpu_percent(interval=None) / psutil.cpu_count()
        
        # I also tried the below code but it was much worse than above
        # for j in range(10):
        #     if j == 0:
        #         test_list = []
        #     p_cpu = self.process.cpu_percent(interval=0.1) / psutil.cpu_count()
        #     test_list.append(p_cpu)
        # process_cpu = (sum(test_list)) / len(test_list)

        # Memory is about 25mb higher than task manager
        process_memory = self.process.memory_info().rss

        print(f"CPU: {process_cpu}")
        print(f"Memory: {process_memory}")

am I using psutil incorrectly or is there a more accurate way to grab the data?我是在错误地使用 psutil 还是有更准确的方法来获取数据?

I think you are misinterpreting the output of psutil.cpu_percent().我认为您误解了 psutil.cpu_percent() 的 output。 Returns a float representing the current system-wide CPU utilization as a percentage.返回一个浮点数,以百分比表示当前系统范围的 CPU 利用率。 When interval is > 0.0 compares process times to system CPU times elapsed before and after the interval (blocking).当间隔大于 0.0 时,将进程时间与间隔(阻塞)前后经过的系统 CPU 时间进行比较。 When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately.当间隔为 0.0 或 None 时,将处理时间与自上次调用以来经过的系统 CPU 时间进行比较,立即返回。 That means that the first time this is called it will return a meaningful 0.0 value on which subsequent calls can be based.这意味着第一次调用它将返回一个有意义的 0.0 值,后续调用可以基于该值。 In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls.在这种情况下,建议以至少 0.1 秒的调用间隔调用此 function 以确保准确。

So, if you call it with interval=0.1, it will return the percentage of time the process was running in the last 0.1 seconds.因此,如果您使用 interval=0.1 调用它,它将返回进程在最后 0.1 秒内运行的时间百分比。 If you call it with interval=None, it will return the percentage of time the process was running since the last time you called it.如果您使用 interval=None 调用它,它将返回自上次调用以来进程运行的时间百分比。 So, if you call it twice in a row with interval=None, the first call will return the percentage of time the process was running since the last time you called it, and the second call will return the percentage of time the process was running since the last time you called it.因此,如果您连续两次调用它且间隔=None,第一次调用将返回自上次调用以来进程运行时间的百分比,第二次调用将返回进程运行时间的百分比自从你上次打电话以来。 So, if you want to get the percentage of time the process was running in the last 0.1 seconds, you should call it with interval=0.1.因此,如果您想获取进程在最后 0.1 秒内运行的时间百分比,您应该使用 interval=0.1 调用它。

this should be more accurate i think?我认为这应该更准确?

    import psutil

for process in [psutil.Process(pid) for pid in psutil.pids()]:
    try:
        process_name = process.name()
        process_mem = process.memory_percent()
        process_cpu = process.cpu_percent(interval=0.5)
    except psutil.NoSuchProcess as e:
        print(e.pid, "killed before analysis")
    else:
        print("Name:", process_name)
        print("CPU%:", process_cpu)
        print("MEM%:", process_mem)

Like @Axeltherabbit mentioned in his comment, Task Manager grabs all processes under a given name, whereas psutils grabs an individual process .就像@Axeltherabbit 在他的评论中提到的那样,任务管理器抓取给定名称下的所有进程,而 psutils 抓取单个进程 psutils is correct, task manager over-scopes and decides to grab all processes. psutils 是正确的,任务管理器超出范围并决定抓取所有进程。

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

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