Skip to content

Commit 5f3906a

Browse files
committed
https://github.com/fabianp/memory_profiler/issues/152
1 parent 1eff08e commit 5f3906a

1 file changed

Lines changed: 26 additions & 3 deletions

File tree

memory_profiler.py

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
import inspect
1717
import subprocess
1818
import logging
19+
import traceback
20+
from signal import SIGKILL
1921

2022

2123
# TODO: provide alternative when multiprocessing is not available
@@ -239,9 +241,9 @@ def run(self):
239241
self.pipe.send(self.n_measurements)
240242

241243

242-
def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False,
243-
include_children=False, multiprocess=False, max_usage=False,
244-
retval=False, stream=None, backend=None):
244+
def memory_usage_actual(proc=-1, interval=.1, timeout=None, timestamps=False,
245+
include_children=False, multiprocess=False, max_usage=False,
246+
retval=False, stream=None, backend=None):
245247
"""
246248
Return the memory usage of a process or piece of code
247249
@@ -424,6 +426,27 @@ def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False,
424426
return ret
425427

426428

429+
def memory_usage(*args, **kwargs):
430+
"""
431+
The wrapper function that calls the memory_usage_actual (see above) function!
432+
433+
When there is an exception in the "proc" - the (spawned) monitoring processes don't get killed.
434+
Therefore, the whole process hangs indefinitely. Here, we are ensuring that the process gets killed!
435+
"""
436+
try:
437+
return memory_usage_actual(*args, **kwargs)
438+
except Exception:
439+
print(traceback.format_exc(), file=sys.stderr)
440+
try: # catch ImportError for psutil
441+
import psutil
442+
parent = psutil.Process(os.getpid())
443+
for child in parent.children(recursive=True):
444+
os.kill(child.pid, SIGKILL)
445+
os.kill(os.getpid(), SIGKILL)
446+
except ImportError:
447+
sys.exit()
448+
449+
427450
# ..
428451
# .. utility functions for line-by-line ..
429452

0 commit comments

Comments
 (0)