4242else :
4343 import builtins
4444
45+
4546 def unicode (x , * args ):
4647 return str (x )
4748
4849# .. get available packages ..
4950try :
5051 import psutil
52+
5153 has_psutil = True
5254except ImportError :
5355 has_psutil = False
5456
5557try :
5658 import tracemalloc
59+
5760 has_tracemalloc = True
5861except ImportError :
5962 has_tracemalloc = False
@@ -67,6 +70,7 @@ class MemitResult(object):
6770
6871 Object based on IPython's TimeitResult
6972 """
73+
7074 def __init__ (self , mem_usage , baseline , repeat , timeout , interval ,
7175 include_children ):
7276 self .mem_usage = mem_usage
@@ -81,13 +85,12 @@ def __str__(self):
8185 inc = max_mem - self .baseline
8286 return 'peak memory: %.02f MiB, increment: %.02f MiB' % (max_mem , inc )
8387
84- def _repr_pretty_ (self , p , cycle ):
88+ def _repr_pretty_ (self , p , cycle ):
8589 msg = str (self )
86- p .text (u'<MemitResult : ' + msg + u'>' )
90+ p .text (u'<MemitResult : ' + msg + u'>' )
8791
8892
8993def _get_memory (pid , timestamps = False , include_children = False , filename = None ):
90-
9194 # .. only for current process and only on unix..
9295 if pid == - 1 :
9396 pid = os .getpid ()
@@ -108,7 +111,8 @@ def ps_util_tool():
108111 try :
109112 # avoid useing get_memory_info since it does not exists
110113 # in psutil > 2.0 and accessing it will cause exception.
111- meminfo_attr = 'memory_info' if hasattr (process , 'memory_info' ) else 'get_memory_info'
114+ meminfo_attr = 'memory_info' if hasattr (process , 'memory_info' ) \
115+ else 'get_memory_info'
112116 mem = getattr (process , meminfo_attr )()[0 ] / _TWO_20
113117 if include_children :
114118 try :
@@ -154,17 +158,23 @@ def posix_tool():
154158 else :
155159 return - 1
156160
157- if _backend == 'tracemalloc' and (filename is None or filename == '<unknown>' ):
158- raise RuntimeError ('There is no access to source file of the profiled function' )
161+ if _backend == 'tracemalloc' and \
162+ (filename is None or filename == '<unknown>' ):
163+ raise RuntimeError (
164+ 'There is no access to source file of the profiled function'
165+ )
159166
160- tools = {'tracemalloc' : tracemalloc_tool , 'psutil' : ps_util_tool , 'posix' : posix_tool }
167+ tools = {'tracemalloc' : tracemalloc_tool ,
168+ 'psutil' : ps_util_tool ,
169+ 'posix' : posix_tool }
161170 return tools [_backend ]()
162171
163172
164173class MemTimer (Process ):
165174 """
166175 Fetch memory consumption from over a time interval
167176 """
177+
168178 def __init__ (self , monitor_pid , interval , pipe , max_usage = False ,
169179 * args , ** kw ):
170180 self .monitor_pid = monitor_pid
@@ -286,8 +296,10 @@ def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False,
286296
287297 while True :
288298 child_conn , parent_conn = Pipe () # this will store MemTimer's results
289- p = MemTimer (os .getpid (), interval , child_conn , timestamps = timestamps ,
290- max_usage = max_usage , include_children = include_children )
299+ p = MemTimer (os .getpid (), interval , child_conn ,
300+ timestamps = timestamps ,
301+ max_usage = max_usage ,
302+ include_children = include_children )
291303 p .start ()
292304 parent_conn .recv () # wait until we start getting memory
293305 returned = f (* args , ** kw )
@@ -359,6 +371,7 @@ def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False,
359371 return None
360372 return ret
361373
374+
362375# ..
363376# .. utility functions for line-by-line ..
364377
@@ -390,16 +403,19 @@ def __init__(self, timestamps, filename):
390403 self ._filename = filename
391404
392405 def __enter__ (self ):
393- self ._timestamps .append (_get_memory (os .getpid (), timestamps = True , filename = self ._filename ))
406+ self ._timestamps .append (
407+ _get_memory (os .getpid (), timestamps = True , filename = self ._filename ))
394408
395409 def __exit__ (self , * args ):
396- self ._timestamps .append (_get_memory (os .getpid (), timestamps = True , filename = self ._filename ))
410+ self ._timestamps .append (
411+ _get_memory (os .getpid (), timestamps = True , filename = self ._filename ))
397412
398413
399414class TimeStamper :
400415 """ A profiler that just records start and end execution times for
401416 any decorated function.
402417 """
418+
403419 def __init__ (self ):
404420 self .functions = {}
405421
@@ -418,6 +434,7 @@ def __call__(self, func=None, precision=None):
418434 else :
419435 def inner_partial (f ):
420436 return self .__call__ (f , precision = precision )
437+
421438 return inner_partial
422439
423440 def timestamp (self , name = "<block>" ):
@@ -444,19 +461,23 @@ def add_function(self, func):
444461 def wrap_function (self , func ):
445462 """ Wrap a function to timestamp it.
446463 """
464+
447465 def f (* args , ** kwds ):
448466 # Start time
449467 try :
450468 filename = inspect .getsourcefile (func )
451469 except TypeError :
452470 filename = '<unknown>'
453- timestamps = [_get_memory (os .getpid (), timestamps = True , filename = filename )]
471+ timestamps = [
472+ _get_memory (os .getpid (), timestamps = True , filename = filename )]
454473 self .functions [func ].append (timestamps )
455474 try :
456475 return func (* args , ** kwds )
457476 finally :
458477 # end time
459- timestamps .append (_get_memory (os .getpid (), timestamps = True , filename = filename ))
478+ timestamps .append (_get_memory (os .getpid (), timestamps = True ,
479+ filename = filename ))
480+
460481 return f
461482
462483 def show_results (self , stream = None ):
@@ -471,7 +492,6 @@ def show_results(self, stream=None):
471492
472493
473494class CodeMap (dict ):
474-
475495 def __init__ (self , include_children ):
476496 self .include_children = include_children
477497 self ._toplevel = []
@@ -487,8 +507,9 @@ def add(self, code, toplevel_code=None):
487507 if not os .path .exists (filename ):
488508 print ('ERROR: Could not find file ' + filename )
489509 if filename .startswith (("ipython-input" , "<ipython-input" )):
490- print ("NOTE: %mprun can only be used on functions defined in "
491- "physical files, and not in the IPython environment." )
510+ print (
511+ "NOTE: %mprun can only be used on functions defined in"
512+ " physical files, and not in the IPython environment." )
492513 return
493514
494515 toplevel_code = code
@@ -504,7 +525,8 @@ def add(self, code, toplevel_code=None):
504525 self .add (subcode , toplevel_code = toplevel_code )
505526
506527 def trace (self , code , lineno ):
507- memory = _get_memory (- 1 , include_children = self .include_children , filename = code .co_filename )
528+ memory = _get_memory (- 1 , include_children = self .include_children ,
529+ filename = code .co_filename )
508530 # if there is already a measurement for that line get the max
509531 previous_memory = self [code ].get (lineno , 0 )
510532 self [code ][lineno ] = max (memory , previous_memory )
@@ -514,7 +536,7 @@ def items(self):
514536 for (filename , code , linenos ) in self ._toplevel :
515537 measures = self [code ]
516538 if not measures :
517- continue # skip if no measurement
539+ continue # skip if no measurement
518540 line_iterator = ((line , measures .get (line )) for line in linenos )
519541 yield (filename , line_iterator )
520542
@@ -541,6 +563,7 @@ def __call__(self, func=None, precision=1):
541563 else :
542564 def inner_partial (f ):
543565 return self .__call__ (f , precision = precision )
566+
544567 return inner_partial
545568
546569 def add_function (self , func ):
@@ -565,6 +588,7 @@ def f(*args, **kwds):
565588 return func (* args , ** kwds )
566589 finally :
567590 self .disable_by_count ()
591+
568592 return f
569593
570594 def run (self , cmd ):
@@ -697,7 +721,6 @@ def _func_exec(stmt, ns):
697721
698722@magics_class
699723class MemoryProfilerMagics (Magics ):
700-
701724 # A lprun-style %mprun magic for IPython.
702725 @line_cell_magic
703726 def mprun (self , parameter_s = '' , cell = None ):
@@ -760,7 +783,8 @@ def mprun(self, parameter_s='', cell=None):
760783 # Escape quote markers.
761784 opts_def = Struct (T = ['' ], f = [])
762785 parameter_s = parameter_s .replace ('"' , r'\"' ).replace ("'" , r"\'" )
763- opts , arg_str = self .parse_options (parameter_s , 'rf:T:c' , list_all = True )
786+ opts , arg_str = self .parse_options (parameter_s , 'rf:T:c' ,
787+ list_all = True )
764788 opts .merge (opts_def )
765789 global_ns = self .shell .user_global_ns
766790 local_ns = self .shell .user_ns
@@ -775,7 +799,8 @@ def mprun(self, parameter_s='', cell=None):
775799 funcs .append (eval (name , global_ns , local_ns ))
776800 except Exception as e :
777801 raise UsageError ('Could not find function %r.\n %s: %s' % (name ,
778- e .__class__ .__name__ , e ))
802+ e .__class__ .__name__ ,
803+ e ))
779804
780805 include_children = 'c' in opts
781806 profile = LineProfiler (include_children = include_children )
@@ -813,14 +838,15 @@ def mprun(self, parameter_s='', cell=None):
813838 page (output , screen_lines = self .shell .rc .screen_length )
814839 else :
815840 page (output )
816- print (message ,)
841+ print (message , )
817842
818843 text_file = opts .T [0 ]
819844 if text_file :
820845 with open (text_file , 'w' ) as pfile :
821846 pfile .write (output )
822- print ('\n *** Profile printout saved to text file %s. %s' % (text_file ,
823- message ))
847+ print ('\n *** Profile printout saved to text file %s. %s' % (
848+ text_file ,
849+ message ))
824850
825851 return_value = None
826852 if 'r' in opts :
@@ -882,7 +908,8 @@ def memit(self, line='', cell=None):
882908
883909 """
884910 from memory_profiler import memory_usage , _func_exec
885- opts , stmt = self .parse_options (line , 'r:t:i:coq' , posix = False , strict = False )
911+ opts , stmt = self .parse_options (line , 'r:t:i:coq' , posix = False ,
912+ strict = False )
886913
887914 if cell is None :
888915 setup = 'pass'
@@ -914,7 +941,8 @@ def memit(self, line='', cell=None):
914941 while counter < repeat :
915942 counter += 1
916943 tmp = memory_usage ((_func_exec , (stmt , self .shell .user_ns )),
917- timeout = timeout , interval = interval , max_usage = True ,
944+ timeout = timeout , interval = interval ,
945+ max_usage = True ,
918946 include_children = include_children )
919947 mem_usage .append (tmp [0 ])
920948
@@ -925,8 +953,9 @@ def memit(self, line='', cell=None):
925953 if mem_usage :
926954 print (result )
927955 else :
928- print ('ERROR: could not read memory usage, try with a lower interval '
929- 'or more iterations' )
956+ print (
957+ 'ERROR: could not read memory usage, try with a lower interval '
958+ 'or more iterations' )
930959
931960 if return_result :
932961 return result
@@ -948,6 +977,7 @@ def register_magics(cls, ip):
948977 else :
949978 ip .register_magics (cls )
950979
980+
951981# commenting out due to failures with some versions of IPython
952982# see https://github.com/fabianp/memory_profiler/issues/106
953983# # Ensuring old interface of magics expose for IPython 0.10
@@ -977,10 +1007,13 @@ def wrapper(*args, **kwargs):
9771007 val = prof (func )(* args , ** kwargs )
9781008 show_results (prof , stream = stream , precision = precision )
9791009 return val
1010+
9801011 return wrapper
9811012 else :
9821013 def inner_wrapper (f ):
983- return profile (f , stream = stream , precision = precision , backend = backend )
1014+ return profile (f , stream = stream , precision = precision ,
1015+ backend = backend )
1016+
9841017 return inner_wrapper
9851018
9861019
@@ -1015,10 +1048,12 @@ def move_to_start(d, key):
10151048 _backend = n_backend
10161049 break
10171050 if _backend == 'no_backend' :
1018- raise NotImplementedError ('Tracemalloc or psutil module is required for non-unix '
1019- 'platforms' )
1051+ raise NotImplementedError (
1052+ 'Tracemalloc or psutil module is required for non-unix '
1053+ 'platforms' )
10201054 if _backend != old_backend :
1021- print ('{} can not be used, {} used instead' .format (old_backend , _backend ))
1055+ print ('{} can not be used, {} used instead' .format (old_backend ,
1056+ _backend ))
10221057 global _backend_chosen
10231058 _backend_chosen = True
10241059
@@ -1050,12 +1085,14 @@ def exec_with_profiler(filename, profiler):
10501085
10511086
10521087class LogFile (object ):
1053- """File-like object to log text using the `logging` module and the log report can be customised."""
1088+ """File-like object to log text using the `logging` module and the log
1089+ report can be customised."""
10541090
10551091 def __init__ (self , name = None , reportIncrementFlag = False ):
10561092 """
10571093 :param name: name of the logger module
1058- reportIncrementFlag: This must be set to True if only the steps with memory increments are to be reported
1094+ reportIncrementFlag: This must be set to True if only the steps
1095+ with memory increments are to be reported
10591096
10601097 :type self: object
10611098 name: string
@@ -1068,7 +1105,8 @@ def write(self, msg, level=logging.INFO):
10681105 if self .reportIncrementFlag :
10691106 if "MiB" in msg and float (msg .split ("MiB" )[1 ].strip ()) > 0 :
10701107 self .logger .log (level , msg )
1071- elif msg .__contains__ ("Filename:" ) or msg .__contains__ ("Line Contents" ):
1108+ elif msg .__contains__ ("Filename:" ) or msg .__contains__ (
1109+ "Line Contents" ):
10721110 self .logger .log (level , msg )
10731111 else :
10741112 self .logger .log (level , msg )
@@ -1080,6 +1118,7 @@ def flush(self):
10801118
10811119if __name__ == '__main__' :
10821120 from optparse import OptionParser
1121+
10831122 parser = OptionParser (usage = _CMD_USAGE , version = __version__ )
10841123 parser .disable_interspersed_args ()
10851124 parser .add_option (
@@ -1097,9 +1136,12 @@ def flush(self):
10971136 action = 'store_true' ,
10981137 help = '''print timestamp instead of memory measurement for
10991138 decorated functions''' )
1100- parser .add_option ('--backend' , dest = 'backend' , type = 'choice' , action = 'store' ,
1101- choices = ['tracemalloc' , 'psutil' , 'posix' ], default = 'psutil' ,
1102- help = 'backend using for getting memory info (one of the {tracemalloc, psutil, posix})' )
1139+ parser .add_option ('--backend' , dest = 'backend' , type = 'choice' ,
1140+ action = 'store' ,
1141+ choices = ['tracemalloc' , 'psutil' , 'posix' ],
1142+ default = 'psutil' ,
1143+ help = 'backend using for getting memory info '
1144+ '(one of the {tracemalloc, psutil, posix})' )
11031145
11041146 if not sys .argv [1 :]:
11051147 parser .print_help ()
0 commit comments