Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find total memory used by Python process and all its children

How can I find the total amount of resident memory used by a Python process and all its forked children?

I know that I can use psutil, for example, to find the percentage of a available physical memory used by the current process like so:

import os
import psutil
current_process = psutil.Process(os.getpid())
mem = current_process.memory_percent()

But I'm looking for the total memory used by a process and its children, if it has any.

like image 633
Will Avatar asked Jun 30 '14 16:06

Will


People also ask

How do I see total memory in Python?

The function psutil. virutal_memory() returns a named tuple about system memory usage. The third field in tuple represents the percentage use of the memory(RAM). It is calculated by (total – available)/total * 100 .

How much memory does Python use?

Those numbers can easily fit in a 64-bit integer, so one would hope Python would store those million integers in no more than ~8MB: a million 8-byte objects. In fact, Python uses more like 35MB of RAM to store these numbers.

How do I check CPU usage in Python?

Use the os Module to Retrieve Current CPU Usage in Python We can use the cpu_count() function from this module to retrieve the CPU usage. The psutil. getloadavg() function provides the load information about the CPU in the form of a tuple. The result obtained from this function gets updated after every five minutes.

Does Python consume more memory?

Python optimizes memory utilization by allocating the same object reference to a new variable if the object already exists with the same value. That is why python is called more memory efficient.


1 Answers

You can use the result from psutil.Process.children() (or psutil.Process.get_children() for older psutil versions) to get all child processes and iterate over them.
It could then look like:

import os
import psutil
current_process = psutil.Process(os.getpid())
mem = current_process.memory_percent()
for child in current_process.children(recursive=True):
    mem += child.memory_percent()

This would sum the percentages of memory used by the main process, its children (forks) and any children's children (if you use recursive=True). You can find this function in the current psutil docs or the old docs.

If you use an older version of psutil than 2 you have to use get_children() instead of children().

like image 200
TobiMarg Avatar answered Oct 01 '22 20:10

TobiMarg