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.
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 .
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.
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.
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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With