88import os
99import time
1010import memory_profiler
11+ from IPython import get_ipython
1112import perf_process
1213
1314# keep a global accounting for the last known memory usage
1819peak_memory_usage = - 1
1920perf_proc = None
2021
22+ watching_memory = True
23+ input_cells = get_ipython ().user_ns ['In' ]
24+
25+
26+ def start_watching_memory ():
27+ """Register memory profiling tools to IPython instance."""
28+ global watching_memory
29+ watching_memory = True
30+ ip = get_ipython ()
31+ ip .events .register ("post_run_cell" , watch_memory )
32+ ip .events .register ("pre_run_cell" , pre_run_cell )
33+
34+
35+ def stop_watching_memory ():
36+ """Unregister memory profiling tools from IPython instance."""
37+ global watching_memory
38+ watching_memory = False
39+ ip = get_ipython ()
40+ try :
41+ ip .events .unregister ("post_run_cell" , watch_memory )
42+ except ValueError :
43+ pass
44+ try :
45+ ip .events .unregister ("pre_run_cell" , pre_run_cell )
46+ except ValueError :
47+ pass
2148
2249def watch_memory ():
2350 import time
2451 # bring in the global memory usage value from the previous iteration
25- global previous_call_memory_usage , peak_memory_usage , keep_watching , perf_proc
26- nbr_commands = len (In )
52+ global previous_call_memory_usage , peak_memory_usage , keep_watching , perf_proc , \
53+ watching_memory , input_cells
54+ #nbr_commands = len(In)
2755 new_memory_usage = memory_profiler .memory_usage ()[0 ]
2856 memory_delta = new_memory_usage - previous_call_memory_usage
2957 keep_watching = False
@@ -42,7 +70,8 @@ def watch_memory():
4270 time .sleep (MIN_TIME_TO_GET_PERF_SAMPLE ) # pause until at least 0.1s has passed
4371 # if we have a valid perf running then capture that information
4472 perf_values = perf_process .finish_perf (perf_proc )
45- cmd = In [nbr_commands - 1 ]
73+
74+ cmd = "" #In[nbr_commands-1]
4675 # convert the results into a pretty string
4776 #output_template = "'{cmd}' used {memory_delta:0.4f} MiB RAM in {time_delta:0.2f}s, peaked {peaked_memory_usage:0.2f} MiB above current, total RAM usage {memory_usage:0.2f} MiB"
4877 output_template = "Used {memory_delta:0.4f} MiB RAM in {time_delta:0.2f}s, peaked {peaked_memory_usage:0.2f} MiB above current, total RAM usage {memory_usage:0.2f} MiB"
@@ -100,16 +129,4 @@ def pre_run_cell():
100129 ipython_memory_usage_thread .start ()
101130
102131 pid = os .getpid ()
103- perf_proc = perf_process .run_capture_perf (pid )
104-
105-
106-
107- if __name__ == "__main__" :
108- if 'In' not in dir ():
109- script_name = os .path .split (__file__ )[1 ]
110- raise ValueError ("You must run this from IPython interactively using e.g. '%run -i {}'" .format (script_name ))
111-
112- ip = get_ipython ()
113- # http://ipython.org/ipython-doc/dev/api/generated/IPython.core.events.html
114- ip .events .register ("post_run_cell" , watch_memory )
115- ip .events .register ("pre_run_cell" , pre_run_cell )
132+ perf_proc = perf_process .run_capture_perf (pid )
0 commit comments