Retrieve the current memory usage of the process and its children. It utilizes the `psutil` library.
()
| 115 | |
| 116 | |
| 117 | def get_memory_info() -> MemoryInfo: |
| 118 | """Retrieve the current memory usage of the process and its children. |
| 119 | |
| 120 | It utilizes the `psutil` library. |
| 121 | """ |
| 122 | logger.debug('Calling get_memory_info()...') |
| 123 | current_process = psutil.Process(os.getpid()) |
| 124 | |
| 125 | # Retrieve estimated memory usage of the current process. |
| 126 | current_size_bytes = _get_used_memory(current_process) |
| 127 | |
| 128 | # Sum memory usage by all children processes, try to exclude shared memory from the sum if allowed by OS. |
| 129 | for child in current_process.children(recursive=True): |
| 130 | # Ignore any NoSuchProcess exception that might occur if a child process ends before we retrieve |
| 131 | # its memory usage. |
| 132 | with suppress(psutil.NoSuchProcess): |
| 133 | current_size_bytes += _get_used_memory(child) |
| 134 | |
| 135 | vm = psutil.virtual_memory() |
| 136 | |
| 137 | return MemoryInfo( |
| 138 | total_size=ByteSize(vm.total), |
| 139 | current_size=ByteSize(current_size_bytes), |
| 140 | system_wide_used_size=ByteSize(vm.total - vm.available), |
| 141 | ) |