Measure CPU or Memory usage of a windows program in Python

Asked

Viewed 551 times

1

Good afternoon!

Guys, I’m new around here. And I’m new with programming too.

My doubt is the following, it is possible to measure the use of CPU or Memory for a program in specific windows using Python?

I am writing a small scrypt, however my scrypt needs a certain task to be executed by a windows program, and only after this task finishes my scrypt continue running.

1 answer

3


Good afternoon, Thiago!

To library psutil provides information about the system, such as memory usage and cpu.

You would start by installing this library in your python virtual environment, using Pip or Conda itself, and then in your code, you should implement import:

import psutil
psutil.cpu_percent()

The above code, for example, returns a float value of the use of the cpu, which can be stored in a variable, for manipulation purposes, to keep the analysis constant of the use of the CPU is just to put the method " psutil.cpu_percent() " inside a looping, for example. A very good command of this library as well, is the: psutil.virtual_memory() that returns the total physical memory, the available memory, the used one, the free, inactive and among others that can be stored inside a python dictionary if written this way:

dict(psutil.virtual_memory()._asdict())

To catch the use of a certain process, I did this example below, which picks up excel:

import psutil

for proc in psutil.process_iter():
        try:
            # Aqui ele pega o nome do processo
            processName = proc.name()
            if processName == 'EXCEL.EXE':
                print(processName , ' ::: ', proc.memory_info().vms) # Esse último comando é para pegar o consumo de VMS pelo processo
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass

The output of the program on my machine was:

EXCEL.EXE ::: 51015680

  • Good evening. It is possible to measure the memory CPU usage for a specific program, like excel?

  • Yes, I edited the question in order to answer your question !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.