I need your help with a psutil script. I want to log memory and CPU usage of a python 2 script in percent. For that I use something similar to the following loop:
while True:
for process in psutil.process_iter():
with process.oneshot():
if process.pid == os.getpid():
metrics_file.write("CPU-%: {} | MEMORY: {}".format(
process.cpu_percent(1)/psutil.cpu_count(),
process.memory_percent()
))
My problem is that the values in the Task Manager are strongly different. CPU-% is consistently two to three times higher, memory-% up to ten times. It appears that I have made an arithmetical mistake, but I cannot see where.
Thank you for your help.
Note: In the task manager, I've checked for the correct PID and switched to percentage values.
Edit: Since I had no success with psutil, I used Windows' performance monitoring tool to log the cpu values as csv files and process them from there on. A guide can be found here. Also, if you want to access the PID with this tool, you can find a way to do so in this post.
All the best! Max