Skip to content

Commit 091d314

Browse files
committed
Feedback
1 parent 2cd5367 commit 091d314

1 file changed

Lines changed: 18 additions & 26 deletions

File tree

memory_profiler.py

Lines changed: 18 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import print_function
2-
31
"""Profile the memory usage of a Python program"""
42

53
# .. we'll use this to pass it to the child script ..
@@ -243,9 +241,9 @@ def run(self):
243241
self.pipe.send(self.n_measurements)
244242

245243

246-
def memory_usage_actual(proc=-1, interval=.1, timeout=None, timestamps=False,
247-
include_children=False, multiprocess=False, max_usage=False,
248-
retval=False, stream=None, backend=None):
244+
def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False,
245+
include_children=False, multiprocess=False, max_usage=False,
246+
retval=False, stream=None, backend=None):
249247
"""
250248
Return the memory usage of a process or piece of code
251249
@@ -335,7 +333,21 @@ def memory_usage_actual(proc=-1, interval=.1, timeout=None, timestamps=False,
335333
include_children=include_children)
336334
p.start()
337335
parent_conn.recv() # wait until we start getting memory
338-
returned = f(*args, **kw)
336+
337+
# When there is an exception in the "proc" - the (spawned) monitoring processes don't get killed.
338+
# Therefore, the whole process hangs indefinitely. Here, we are ensuring that the process gets killed!
339+
try:
340+
returned = f(*args, **kw)
341+
except Exception:
342+
sys.stderr.write(traceback.format_exc())
343+
if has_psutil:
344+
parent = psutil.Process(os.getpid())
345+
for child in parent.children(recursive=True):
346+
os.kill(child.pid, SIGKILL)
347+
os.kill(os.getpid(), SIGKILL)
348+
else:
349+
sys.exit()
350+
339351
parent_conn.send(0) # finish timing
340352
ret = parent_conn.recv()
341353
n_measurements = parent_conn.recv()
@@ -428,26 +440,6 @@ def memory_usage_actual(proc=-1, interval=.1, timeout=None, timestamps=False,
428440
return ret
429441

430442

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

0 commit comments

Comments
 (0)