@@ -49,6 +49,28 @@ def unicode(x, *args): return str(x)
4949 has_psutil = False
5050
5151
52+ class MemitResult (object ):
53+ """memit magic run details.
54+
55+ Object based on IPython's TimeitResult
56+ """
57+ def __init__ (self , mem_usage , baseline , repeat , timeout , interval ,
58+ include_children ):
59+ self .mem_usage = mem_usage
60+ self .baseline = baseline
61+ self .repeat = repeat
62+ self .timeout = timeout
63+ self .interval = interval
64+ self .include_children = include_children
65+
66+ def _repr_pretty_ (self , p , cycle ):
67+ max_mem = max (self .mem_usage )
68+ inc = max_mem - self .baseline
69+ msg = 'peak memory: %.02f MiB, increment: %.02f MiB' % (max_mem , inc )
70+
71+ p .text (u'<MemitResult : ' + msg + u'>' )
72+
73+
5274def _get_memory (pid , timestamps = False , include_children = False ):
5375
5476 # .. only for current process and only on unix..
@@ -794,6 +816,7 @@ def memit(self, line='', cell=None):
794816
795817 -c: If present, add the memory usage of any children process to the report.
796818
819+ -o: If present, return a object containing memit run details
797820 Examples
798821 --------
799822 ::
@@ -811,7 +834,7 @@ def memit(self, line='', cell=None):
811834
812835 """
813836 from memory_profiler import memory_usage , _func_exec
814- opts , stmt = self .parse_options (line , 'r:t:i:c ' , posix = False , strict = False )
837+ opts , stmt = self .parse_options (line , 'r:t:i:co ' , posix = False , strict = False )
815838
816839 if cell is None :
817840 setup = 'pass'
@@ -827,6 +850,7 @@ def memit(self, line='', cell=None):
827850 timeout = None
828851 interval = float (getattr (opts , 'i' , 0.1 ))
829852 include_children = 'c' in opts
853+ return_result = 'o' in opts
830854
831855 # I've noticed we get less noisier measurements if we run
832856 # a garbage collection first
@@ -835,23 +859,28 @@ def memit(self, line='', cell=None):
835859
836860 _func_exec (setup , self .shell .user_ns )
837861
838- mem_usage = 0
862+ mem_usage = []
839863 counter = 0
840864 baseline = memory_usage ()[0 ]
841865 while counter < repeat :
842866 counter += 1
843867 tmp = memory_usage ((_func_exec , (stmt , self .shell .user_ns )),
844868 timeout = timeout , interval = interval , max_usage = True ,
845869 include_children = include_children )
846- mem_usage = max ( mem_usage , tmp [0 ])
870+ mem_usage . append ( tmp [0 ])
847871
848872 if mem_usage :
873+ max_mem = max (mem_usage )
849874 print ('peak memory: %.02f MiB, increment: %.02f MiB' %
850- (mem_usage , mem_usage - baseline ))
875+ (max_mem , max_mem - baseline ))
851876 else :
852877 print ('ERROR: could not read memory usage, try with a lower interval '
853878 'or more iterations' )
854879
880+ if return_result :
881+ return MemitResult (mem_usage , baseline , repeat , timeout , interval ,
882+ include_children )
883+
855884 @classmethod
856885 def register_magics (cls , ip ):
857886 from distutils .version import LooseVersion
0 commit comments