(pid, backend, timestamps=False, include_children=False, filename=None)
| 115 | |
| 116 | |
| 117 | def _get_memory(pid, backend, timestamps=False, include_children=False, filename=None): |
| 118 | # .. low function to get memory consumption .. |
| 119 | if pid == -1: |
| 120 | pid = os.getpid() |
| 121 | |
| 122 | def tracemalloc_tool(): |
| 123 | # .. cross-platform but but requires Python 3.4 or higher .. |
| 124 | stat = next(filter(lambda item: str(item).startswith(filename), |
| 125 | tracemalloc.take_snapshot().statistics('filename'))) |
| 126 | mem = stat.size / _TWO_20 |
| 127 | if timestamps: |
| 128 | return mem, time.time() |
| 129 | else: |
| 130 | return mem |
| 131 | |
| 132 | def ps_util_tool(): |
| 133 | # .. cross-platform but but requires psutil .. |
| 134 | process = psutil.Process(pid) |
| 135 | try: |
| 136 | # avoid using get_memory_info since it does not exists |
| 137 | # in psutil > 2.0 and accessing it will cause exception. |
| 138 | meminfo_attr = 'memory_info' if hasattr(process, 'memory_info') \ |
| 139 | else 'get_memory_info' |
| 140 | mem = getattr(process, meminfo_attr)()[0] / _TWO_20 |
| 141 | if include_children: |
| 142 | mem += sum([mem for (pid, mem) in _get_child_memory(process, meminfo_attr)]) |
| 143 | if timestamps: |
| 144 | return mem, time.time() |
| 145 | else: |
| 146 | return mem |
| 147 | except psutil.AccessDenied: |
| 148 | pass |
| 149 | # continue and try to get this from ps |
| 150 | |
| 151 | def _ps_util_full_tool(memory_metric): |
| 152 | |
| 153 | # .. cross-platform but requires psutil > 4.0.0 .. |
| 154 | process = psutil.Process(pid) |
| 155 | try: |
| 156 | if not hasattr(process, 'memory_full_info'): |
| 157 | raise NotImplementedError("Backend `{}` requires psutil > 4.0.0".format(memory_metric)) |
| 158 | |
| 159 | meminfo_attr = 'memory_full_info' |
| 160 | meminfo = getattr(process, meminfo_attr)() |
| 161 | |
| 162 | if not hasattr(meminfo, memory_metric): |
| 163 | raise NotImplementedError( |
| 164 | "Metric `{}` not available. For details, see:".format(memory_metric) + |
| 165 | "https://psutil.readthedocs.io/en/latest/index.html?highlight=memory_info#psutil.Process.memory_full_info") |
| 166 | mem = getattr(meminfo, memory_metric) / _TWO_20 |
| 167 | |
| 168 | if include_children: |
| 169 | mem += sum([mem for (pid, mem) in _get_child_memory(process, meminfo_attr, memory_metric)]) |
| 170 | |
| 171 | if timestamps: |
| 172 | return mem, time.time() |
| 173 | else: |
| 174 | return mem |
no test coverage detected