|
16 | 16 | import inspect |
17 | 17 | import subprocess |
18 | 18 | import logging |
| 19 | +import traceback |
| 20 | +from signal import SIGKILL |
19 | 21 |
|
20 | 22 |
|
21 | 23 | # TODO: provide alternative when multiprocessing is not available |
@@ -239,9 +241,9 @@ def run(self): |
239 | 241 | self.pipe.send(self.n_measurements) |
240 | 242 |
|
241 | 243 |
|
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): |
245 | 247 | """ |
246 | 248 | Return the memory usage of a process or piece of code |
247 | 249 |
|
@@ -424,6 +426,27 @@ def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False, |
424 | 426 | return ret |
425 | 427 |
|
426 | 428 |
|
| 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 | + |
427 | 450 | # .. |
428 | 451 | # .. utility functions for line-by-line .. |
429 | 452 |
|
|
0 commit comments