3

Suppose we want to find out how much energy, CPU and RAM are being used in Python to find out the factorial of a positive integer. I used the code below but it is not working.

MWE:

from __future__ import print_function
import psutil

n=5
fact=1
for i in range(1,n+1):
    fact=fact*i
print fact

print('CPU  % used:', psutil.cpu_percent())
print('physical memory  % used:', psutil.virtual_memory())  # physical memory usage
print('memory % used:', psutil.virtual_memory()[2])
BSFU
  • 59
  • 1
  • 7

1 Answers1

1

You want to use psutil.Process(pid=None). Note on the documentation:

If pid is omitted current process pid (os.getpid) is used.

Therefore, you can simply do:

import psutil


process = psutil.Process()
memory = process.memory_percent()
cpu = process.cpu_percent()

print(memory, cpu)

The above is for memory and CPU percentage use only. I recommend reading further into the documentation to figure out exactly what you need.

felipe
  • 7,324
  • 2
  • 28
  • 37