##// END OF EJS Templates
Refactor ExecutionMagics._run_with_profiler
Takafumi Arakaki -
Show More
@@ -1,1155 +1,1127 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions.
2 """Implementation of execution-related magic functions.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (c) 2012 The IPython Development Team.
5 # Copyright (c) 2012 The IPython Development Team.
6 #
6 #
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8 #
8 #
9 # The full license is in the file COPYING.txt, distributed with this software.
9 # The full license is in the file COPYING.txt, distributed with this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Imports
13 # Imports
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 # Stdlib
16 # Stdlib
17 import __builtin__ as builtin_mod
17 import __builtin__ as builtin_mod
18 import ast
18 import ast
19 import bdb
19 import bdb
20 import os
20 import os
21 import sys
21 import sys
22 import time
22 import time
23 from StringIO import StringIO
23 from StringIO import StringIO
24
24
25 # cProfile was added in Python2.5
25 # cProfile was added in Python2.5
26 try:
26 try:
27 import cProfile as profile
27 import cProfile as profile
28 import pstats
28 import pstats
29 except ImportError:
29 except ImportError:
30 # profile isn't bundled by default in Debian for license reasons
30 # profile isn't bundled by default in Debian for license reasons
31 try:
31 try:
32 import profile, pstats
32 import profile, pstats
33 except ImportError:
33 except ImportError:
34 profile = pstats = None
34 profile = pstats = None
35
35
36 # Our own packages
36 # Our own packages
37 from IPython.core import debugger, oinspect
37 from IPython.core import debugger, oinspect
38 from IPython.core import magic_arguments
38 from IPython.core import magic_arguments
39 from IPython.core import page
39 from IPython.core import page
40 from IPython.core.error import UsageError
40 from IPython.core.error import UsageError
41 from IPython.core.macro import Macro
41 from IPython.core.macro import Macro
42 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
42 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
43 line_cell_magic, on_off, needs_local_scope)
43 line_cell_magic, on_off, needs_local_scope)
44 from IPython.testing.skipdoctest import skip_doctest
44 from IPython.testing.skipdoctest import skip_doctest
45 from IPython.utils import py3compat
45 from IPython.utils import py3compat
46 from IPython.utils.contexts import preserve_keys
46 from IPython.utils.contexts import preserve_keys
47 from IPython.utils.io import capture_output
47 from IPython.utils.io import capture_output
48 from IPython.utils.ipstruct import Struct
48 from IPython.utils.ipstruct import Struct
49 from IPython.utils.module_paths import find_mod
49 from IPython.utils.module_paths import find_mod
50 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
50 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
51 from IPython.utils.timing import clock, clock2
51 from IPython.utils.timing import clock, clock2
52 from IPython.utils.warn import warn, error
52 from IPython.utils.warn import warn, error
53
53
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Magic implementation classes
56 # Magic implementation classes
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 @magics_class
59 @magics_class
60 class ExecutionMagics(Magics):
60 class ExecutionMagics(Magics):
61 """Magics related to code execution, debugging, profiling, etc.
61 """Magics related to code execution, debugging, profiling, etc.
62
62
63 """
63 """
64
64
65 def __init__(self, shell):
65 def __init__(self, shell):
66 super(ExecutionMagics, self).__init__(shell)
66 super(ExecutionMagics, self).__init__(shell)
67 if profile is None:
67 if profile is None:
68 self.prun = self.profile_missing_notice
68 self.prun = self.profile_missing_notice
69 # Default execution function used to actually run user code.
69 # Default execution function used to actually run user code.
70 self.default_runner = None
70 self.default_runner = None
71
71
72 def profile_missing_notice(self, *args, **kwargs):
72 def profile_missing_notice(self, *args, **kwargs):
73 error("""\
73 error("""\
74 The profile module could not be found. It has been removed from the standard
74 The profile module could not be found. It has been removed from the standard
75 python packages because of its non-free license. To use profiling, install the
75 python packages because of its non-free license. To use profiling, install the
76 python-profiler package from non-free.""")
76 python-profiler package from non-free.""")
77
77
78 @skip_doctest
78 @skip_doctest
79 @line_cell_magic
79 @line_cell_magic
80 def prun(self, parameter_s='', cell=None):
80 def prun(self, parameter_s='', cell=None):
81
81
82 """Run a statement through the python code profiler.
82 """Run a statement through the python code profiler.
83
83
84 Usage, in line mode:
84 Usage, in line mode:
85 %prun [options] statement
85 %prun [options] statement
86
86
87 Usage, in cell mode:
87 Usage, in cell mode:
88 %%prun [options] [statement]
88 %%prun [options] [statement]
89 code...
89 code...
90 code...
90 code...
91
91
92 In cell mode, the additional code lines are appended to the (possibly
92 In cell mode, the additional code lines are appended to the (possibly
93 empty) statement in the first line. Cell mode allows you to easily
93 empty) statement in the first line. Cell mode allows you to easily
94 profile multiline blocks without having to put them in a separate
94 profile multiline blocks without having to put them in a separate
95 function.
95 function.
96
96
97 The given statement (which doesn't require quote marks) is run via the
97 The given statement (which doesn't require quote marks) is run via the
98 python profiler in a manner similar to the profile.run() function.
98 python profiler in a manner similar to the profile.run() function.
99 Namespaces are internally managed to work correctly; profile.run
99 Namespaces are internally managed to work correctly; profile.run
100 cannot be used in IPython because it makes certain assumptions about
100 cannot be used in IPython because it makes certain assumptions about
101 namespaces which do not hold under IPython.
101 namespaces which do not hold under IPython.
102
102
103 Options:
103 Options:
104
104
105 -l <limit>: you can place restrictions on what or how much of the
105 -l <limit>: you can place restrictions on what or how much of the
106 profile gets printed. The limit value can be:
106 profile gets printed. The limit value can be:
107
107
108 * A string: only information for function names containing this string
108 * A string: only information for function names containing this string
109 is printed.
109 is printed.
110
110
111 * An integer: only these many lines are printed.
111 * An integer: only these many lines are printed.
112
112
113 * A float (between 0 and 1): this fraction of the report is printed
113 * A float (between 0 and 1): this fraction of the report is printed
114 (for example, use a limit of 0.4 to see the topmost 40% only).
114 (for example, use a limit of 0.4 to see the topmost 40% only).
115
115
116 You can combine several limits with repeated use of the option. For
116 You can combine several limits with repeated use of the option. For
117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
118 information about class constructors.
118 information about class constructors.
119
119
120 -r: return the pstats.Stats object generated by the profiling. This
120 -r: return the pstats.Stats object generated by the profiling. This
121 object has all the information about the profile in it, and you can
121 object has all the information about the profile in it, and you can
122 later use it for further analysis or in other functions.
122 later use it for further analysis or in other functions.
123
123
124 -s <key>: sort profile by given key. You can provide more than one key
124 -s <key>: sort profile by given key. You can provide more than one key
125 by using the option several times: '-s key1 -s key2 -s key3...'. The
125 by using the option several times: '-s key1 -s key2 -s key3...'. The
126 default sorting key is 'time'.
126 default sorting key is 'time'.
127
127
128 The following is copied verbatim from the profile documentation
128 The following is copied verbatim from the profile documentation
129 referenced below:
129 referenced below:
130
130
131 When more than one key is provided, additional keys are used as
131 When more than one key is provided, additional keys are used as
132 secondary criteria when the there is equality in all keys selected
132 secondary criteria when the there is equality in all keys selected
133 before them.
133 before them.
134
134
135 Abbreviations can be used for any key names, as long as the
135 Abbreviations can be used for any key names, as long as the
136 abbreviation is unambiguous. The following are the keys currently
136 abbreviation is unambiguous. The following are the keys currently
137 defined:
137 defined:
138
138
139 Valid Arg Meaning
139 Valid Arg Meaning
140 "calls" call count
140 "calls" call count
141 "cumulative" cumulative time
141 "cumulative" cumulative time
142 "file" file name
142 "file" file name
143 "module" file name
143 "module" file name
144 "pcalls" primitive call count
144 "pcalls" primitive call count
145 "line" line number
145 "line" line number
146 "name" function name
146 "name" function name
147 "nfl" name/file/line
147 "nfl" name/file/line
148 "stdname" standard name
148 "stdname" standard name
149 "time" internal time
149 "time" internal time
150
150
151 Note that all sorts on statistics are in descending order (placing
151 Note that all sorts on statistics are in descending order (placing
152 most time consuming items first), where as name, file, and line number
152 most time consuming items first), where as name, file, and line number
153 searches are in ascending order (i.e., alphabetical). The subtle
153 searches are in ascending order (i.e., alphabetical). The subtle
154 distinction between "nfl" and "stdname" is that the standard name is a
154 distinction between "nfl" and "stdname" is that the standard name is a
155 sort of the name as printed, which means that the embedded line
155 sort of the name as printed, which means that the embedded line
156 numbers get compared in an odd way. For example, lines 3, 20, and 40
156 numbers get compared in an odd way. For example, lines 3, 20, and 40
157 would (if the file names were the same) appear in the string order
157 would (if the file names were the same) appear in the string order
158 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
158 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
159 line numbers. In fact, sort_stats("nfl") is the same as
159 line numbers. In fact, sort_stats("nfl") is the same as
160 sort_stats("name", "file", "line").
160 sort_stats("name", "file", "line").
161
161
162 -T <filename>: save profile results as shown on screen to a text
162 -T <filename>: save profile results as shown on screen to a text
163 file. The profile is still shown on screen.
163 file. The profile is still shown on screen.
164
164
165 -D <filename>: save (via dump_stats) profile statistics to given
165 -D <filename>: save (via dump_stats) profile statistics to given
166 filename. This data is in a format understood by the pstats module, and
166 filename. This data is in a format understood by the pstats module, and
167 is generated by a call to the dump_stats() method of profile
167 is generated by a call to the dump_stats() method of profile
168 objects. The profile is still shown on screen.
168 objects. The profile is still shown on screen.
169
169
170 -q: suppress output to the pager. Best used with -T and/or -D above.
170 -q: suppress output to the pager. Best used with -T and/or -D above.
171
171
172 If you want to run complete programs under the profiler's control, use
172 If you want to run complete programs under the profiler's control, use
173 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
173 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
174 contains profiler specific options as described here.
174 contains profiler specific options as described here.
175
175
176 You can read the complete documentation for the profile module with::
176 You can read the complete documentation for the profile module with::
177
177
178 In [1]: import profile; profile.help()
178 In [1]: import profile; profile.help()
179 """
179 """
180 return self._run_with_profiler(parameter_s, cell)
180 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
181
181 list_all=True, posix=False)
182 def _run_with_profiler(
182 if cell is not None:
183 self, parameter_s='', cell=None, user_mode=True,
183 arg_str += '\n' + cell
184 opts=None, arg_lst=None, prog_ns=None, namespace=None):
184 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
185
186 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
187
188 if user_mode: # regular user call
189 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
190 list_all=True, posix=False)
191 namespace = self.shell.user_ns
192 if cell is not None:
193 arg_str += '\n' + cell
194 elif namespace is not None: # called to run a program by %run -p
195 arg_str = cell
196 else:
197 try:
198 filename = get_py_filename(arg_lst[0])
199 except IOError as e:
200 try:
201 msg = str(e)
202 except UnicodeError:
203 msg = e.message
204 error(msg)
205 return
206
185
207 arg_str = 'execfile(filename,prog_ns)'
186 def _run_with_profiler(self, arg_str, opts, namespace):
208 namespace = {
209 'execfile': self.shell.safe_execfile,
210 'prog_ns': prog_ns,
211 'filename': filename
212 }
213
187
214 opts.merge(opts_def)
188 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
215
189
216 prof = profile.Profile()
190 prof = profile.Profile()
217 try:
191 try:
218 prof = prof.runctx(arg_str,namespace,namespace)
192 prof = prof.runctx(arg_str,namespace,namespace)
219 sys_exit = ''
193 sys_exit = ''
220 except SystemExit:
194 except SystemExit:
221 sys_exit = """*** SystemExit exception caught in code being profiled."""
195 sys_exit = """*** SystemExit exception caught in code being profiled."""
222
196
223 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
197 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
224
198
225 lims = opts.l
199 lims = opts.l
226 if lims:
200 if lims:
227 lims = [] # rebuild lims with ints/floats/strings
201 lims = [] # rebuild lims with ints/floats/strings
228 for lim in opts.l:
202 for lim in opts.l:
229 try:
203 try:
230 lims.append(int(lim))
204 lims.append(int(lim))
231 except ValueError:
205 except ValueError:
232 try:
206 try:
233 lims.append(float(lim))
207 lims.append(float(lim))
234 except ValueError:
208 except ValueError:
235 lims.append(lim)
209 lims.append(lim)
236
210
237 # Trap output.
211 # Trap output.
238 stdout_trap = StringIO()
212 stdout_trap = StringIO()
239 stats_stream = stats.stream
213 stats_stream = stats.stream
240 try:
214 try:
241 stats.stream = stdout_trap
215 stats.stream = stdout_trap
242 stats.print_stats(*lims)
216 stats.print_stats(*lims)
243 finally:
217 finally:
244 stats.stream = stats_stream
218 stats.stream = stats_stream
245
219
246 output = stdout_trap.getvalue()
220 output = stdout_trap.getvalue()
247 output = output.rstrip()
221 output = output.rstrip()
248
222
249 if 'q' not in opts:
223 if 'q' not in opts:
250 page.page(output)
224 page.page(output)
251 print sys_exit,
225 print sys_exit,
252
226
253 dump_file = opts.D[0]
227 dump_file = opts.D[0]
254 text_file = opts.T[0]
228 text_file = opts.T[0]
255 if dump_file:
229 if dump_file:
256 dump_file = unquote_filename(dump_file)
230 dump_file = unquote_filename(dump_file)
257 prof.dump_stats(dump_file)
231 prof.dump_stats(dump_file)
258 print '\n*** Profile stats marshalled to file',\
232 print '\n*** Profile stats marshalled to file',\
259 repr(dump_file)+'.',sys_exit
233 repr(dump_file)+'.',sys_exit
260 if text_file:
234 if text_file:
261 text_file = unquote_filename(text_file)
235 text_file = unquote_filename(text_file)
262 pfile = open(text_file,'w')
236 pfile = open(text_file,'w')
263 pfile.write(output)
237 pfile.write(output)
264 pfile.close()
238 pfile.close()
265 print '\n*** Profile printout saved to text file',\
239 print '\n*** Profile printout saved to text file',\
266 repr(text_file)+'.',sys_exit
240 repr(text_file)+'.',sys_exit
267
241
268 if 'r' in opts:
242 if 'r' in opts:
269 return stats
243 return stats
270 else:
244 else:
271 return None
245 return None
272
246
273 @line_magic
247 @line_magic
274 def pdb(self, parameter_s=''):
248 def pdb(self, parameter_s=''):
275 """Control the automatic calling of the pdb interactive debugger.
249 """Control the automatic calling of the pdb interactive debugger.
276
250
277 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
251 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
278 argument it works as a toggle.
252 argument it works as a toggle.
279
253
280 When an exception is triggered, IPython can optionally call the
254 When an exception is triggered, IPython can optionally call the
281 interactive pdb debugger after the traceback printout. %pdb toggles
255 interactive pdb debugger after the traceback printout. %pdb toggles
282 this feature on and off.
256 this feature on and off.
283
257
284 The initial state of this feature is set in your configuration
258 The initial state of this feature is set in your configuration
285 file (the option is ``InteractiveShell.pdb``).
259 file (the option is ``InteractiveShell.pdb``).
286
260
287 If you want to just activate the debugger AFTER an exception has fired,
261 If you want to just activate the debugger AFTER an exception has fired,
288 without having to type '%pdb on' and rerunning your code, you can use
262 without having to type '%pdb on' and rerunning your code, you can use
289 the %debug magic."""
263 the %debug magic."""
290
264
291 par = parameter_s.strip().lower()
265 par = parameter_s.strip().lower()
292
266
293 if par:
267 if par:
294 try:
268 try:
295 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
269 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
296 except KeyError:
270 except KeyError:
297 print ('Incorrect argument. Use on/1, off/0, '
271 print ('Incorrect argument. Use on/1, off/0, '
298 'or nothing for a toggle.')
272 'or nothing for a toggle.')
299 return
273 return
300 else:
274 else:
301 # toggle
275 # toggle
302 new_pdb = not self.shell.call_pdb
276 new_pdb = not self.shell.call_pdb
303
277
304 # set on the shell
278 # set on the shell
305 self.shell.call_pdb = new_pdb
279 self.shell.call_pdb = new_pdb
306 print 'Automatic pdb calling has been turned',on_off(new_pdb)
280 print 'Automatic pdb calling has been turned',on_off(new_pdb)
307
281
308 @line_magic
282 @line_magic
309 def debug(self, parameter_s=''):
283 def debug(self, parameter_s=''):
310 """Activate the interactive debugger in post-mortem mode.
284 """Activate the interactive debugger in post-mortem mode.
311
285
312 If an exception has just occurred, this lets you inspect its stack
286 If an exception has just occurred, this lets you inspect its stack
313 frames interactively. Note that this will always work only on the last
287 frames interactively. Note that this will always work only on the last
314 traceback that occurred, so you must call this quickly after an
288 traceback that occurred, so you must call this quickly after an
315 exception that you wish to inspect has fired, because if another one
289 exception that you wish to inspect has fired, because if another one
316 occurs, it clobbers the previous one.
290 occurs, it clobbers the previous one.
317
291
318 If you want IPython to automatically do this on every exception, see
292 If you want IPython to automatically do this on every exception, see
319 the %pdb magic for more details.
293 the %pdb magic for more details.
320 """
294 """
321 self.shell.debugger(force=True)
295 self.shell.debugger(force=True)
322
296
323 @line_magic
297 @line_magic
324 def tb(self, s):
298 def tb(self, s):
325 """Print the last traceback with the currently active exception mode.
299 """Print the last traceback with the currently active exception mode.
326
300
327 See %xmode for changing exception reporting modes."""
301 See %xmode for changing exception reporting modes."""
328 self.shell.showtraceback()
302 self.shell.showtraceback()
329
303
330 @skip_doctest
304 @skip_doctest
331 @line_magic
305 @line_magic
332 def run(self, parameter_s='', runner=None,
306 def run(self, parameter_s='', runner=None,
333 file_finder=get_py_filename):
307 file_finder=get_py_filename):
334 """Run the named file inside IPython as a program.
308 """Run the named file inside IPython as a program.
335
309
336 Usage:\\
310 Usage:\\
337 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args]
311 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args]
338
312
339 Parameters after the filename are passed as command-line arguments to
313 Parameters after the filename are passed as command-line arguments to
340 the program (put in sys.argv). Then, control returns to IPython's
314 the program (put in sys.argv). Then, control returns to IPython's
341 prompt.
315 prompt.
342
316
343 This is similar to running at a system prompt:\\
317 This is similar to running at a system prompt:\\
344 $ python file args\\
318 $ python file args\\
345 but with the advantage of giving you IPython's tracebacks, and of
319 but with the advantage of giving you IPython's tracebacks, and of
346 loading all variables into your interactive namespace for further use
320 loading all variables into your interactive namespace for further use
347 (unless -p is used, see below).
321 (unless -p is used, see below).
348
322
349 The file is executed in a namespace initially consisting only of
323 The file is executed in a namespace initially consisting only of
350 __name__=='__main__' and sys.argv constructed as indicated. It thus
324 __name__=='__main__' and sys.argv constructed as indicated. It thus
351 sees its environment as if it were being run as a stand-alone program
325 sees its environment as if it were being run as a stand-alone program
352 (except for sharing global objects such as previously imported
326 (except for sharing global objects such as previously imported
353 modules). But after execution, the IPython interactive namespace gets
327 modules). But after execution, the IPython interactive namespace gets
354 updated with all variables defined in the program (except for __name__
328 updated with all variables defined in the program (except for __name__
355 and sys.argv). This allows for very convenient loading of code for
329 and sys.argv). This allows for very convenient loading of code for
356 interactive work, while giving each program a 'clean sheet' to run in.
330 interactive work, while giving each program a 'clean sheet' to run in.
357
331
358 Arguments are expanded using shell-like glob match. Patterns
332 Arguments are expanded using shell-like glob match. Patterns
359 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
333 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
360 tilde '~' will be expanded into user's home directory. Unlike
334 tilde '~' will be expanded into user's home directory. Unlike
361 real shells, quotation does not suppress expansions. Use
335 real shells, quotation does not suppress expansions. Use
362 *two* back slashes (e.g., '\\\\*') to suppress expansions.
336 *two* back slashes (e.g., '\\\\*') to suppress expansions.
363 To completely disable these expansions, you can use -G flag.
337 To completely disable these expansions, you can use -G flag.
364
338
365 Options:
339 Options:
366
340
367 -n: __name__ is NOT set to '__main__', but to the running file's name
341 -n: __name__ is NOT set to '__main__', but to the running file's name
368 without extension (as python does under import). This allows running
342 without extension (as python does under import). This allows running
369 scripts and reloading the definitions in them without calling code
343 scripts and reloading the definitions in them without calling code
370 protected by an ' if __name__ == "__main__" ' clause.
344 protected by an ' if __name__ == "__main__" ' clause.
371
345
372 -i: run the file in IPython's namespace instead of an empty one. This
346 -i: run the file in IPython's namespace instead of an empty one. This
373 is useful if you are experimenting with code written in a text editor
347 is useful if you are experimenting with code written in a text editor
374 which depends on variables defined interactively.
348 which depends on variables defined interactively.
375
349
376 -e: ignore sys.exit() calls or SystemExit exceptions in the script
350 -e: ignore sys.exit() calls or SystemExit exceptions in the script
377 being run. This is particularly useful if IPython is being used to
351 being run. This is particularly useful if IPython is being used to
378 run unittests, which always exit with a sys.exit() call. In such
352 run unittests, which always exit with a sys.exit() call. In such
379 cases you are interested in the output of the test results, not in
353 cases you are interested in the output of the test results, not in
380 seeing a traceback of the unittest module.
354 seeing a traceback of the unittest module.
381
355
382 -t: print timing information at the end of the run. IPython will give
356 -t: print timing information at the end of the run. IPython will give
383 you an estimated CPU time consumption for your script, which under
357 you an estimated CPU time consumption for your script, which under
384 Unix uses the resource module to avoid the wraparound problems of
358 Unix uses the resource module to avoid the wraparound problems of
385 time.clock(). Under Unix, an estimate of time spent on system tasks
359 time.clock(). Under Unix, an estimate of time spent on system tasks
386 is also given (for Windows platforms this is reported as 0.0).
360 is also given (for Windows platforms this is reported as 0.0).
387
361
388 If -t is given, an additional -N<N> option can be given, where <N>
362 If -t is given, an additional -N<N> option can be given, where <N>
389 must be an integer indicating how many times you want the script to
363 must be an integer indicating how many times you want the script to
390 run. The final timing report will include total and per run results.
364 run. The final timing report will include total and per run results.
391
365
392 For example (testing the script uniq_stable.py)::
366 For example (testing the script uniq_stable.py)::
393
367
394 In [1]: run -t uniq_stable
368 In [1]: run -t uniq_stable
395
369
396 IPython CPU timings (estimated):\\
370 IPython CPU timings (estimated):\\
397 User : 0.19597 s.\\
371 User : 0.19597 s.\\
398 System: 0.0 s.\\
372 System: 0.0 s.\\
399
373
400 In [2]: run -t -N5 uniq_stable
374 In [2]: run -t -N5 uniq_stable
401
375
402 IPython CPU timings (estimated):\\
376 IPython CPU timings (estimated):\\
403 Total runs performed: 5\\
377 Total runs performed: 5\\
404 Times : Total Per run\\
378 Times : Total Per run\\
405 User : 0.910862 s, 0.1821724 s.\\
379 User : 0.910862 s, 0.1821724 s.\\
406 System: 0.0 s, 0.0 s.
380 System: 0.0 s, 0.0 s.
407
381
408 -d: run your program under the control of pdb, the Python debugger.
382 -d: run your program under the control of pdb, the Python debugger.
409 This allows you to execute your program step by step, watch variables,
383 This allows you to execute your program step by step, watch variables,
410 etc. Internally, what IPython does is similar to calling:
384 etc. Internally, what IPython does is similar to calling:
411
385
412 pdb.run('execfile("YOURFILENAME")')
386 pdb.run('execfile("YOURFILENAME")')
413
387
414 with a breakpoint set on line 1 of your file. You can change the line
388 with a breakpoint set on line 1 of your file. You can change the line
415 number for this automatic breakpoint to be <N> by using the -bN option
389 number for this automatic breakpoint to be <N> by using the -bN option
416 (where N must be an integer). For example::
390 (where N must be an integer). For example::
417
391
418 %run -d -b40 myscript
392 %run -d -b40 myscript
419
393
420 will set the first breakpoint at line 40 in myscript.py. Note that
394 will set the first breakpoint at line 40 in myscript.py. Note that
421 the first breakpoint must be set on a line which actually does
395 the first breakpoint must be set on a line which actually does
422 something (not a comment or docstring) for it to stop execution.
396 something (not a comment or docstring) for it to stop execution.
423
397
424 Or you can specify a breakpoint in a different file::
398 Or you can specify a breakpoint in a different file::
425
399
426 %run -d -b myotherfile.py:20 myscript
400 %run -d -b myotherfile.py:20 myscript
427
401
428 When the pdb debugger starts, you will see a (Pdb) prompt. You must
402 When the pdb debugger starts, you will see a (Pdb) prompt. You must
429 first enter 'c' (without quotes) to start execution up to the first
403 first enter 'c' (without quotes) to start execution up to the first
430 breakpoint.
404 breakpoint.
431
405
432 Entering 'help' gives information about the use of the debugger. You
406 Entering 'help' gives information about the use of the debugger. You
433 can easily see pdb's full documentation with "import pdb;pdb.help()"
407 can easily see pdb's full documentation with "import pdb;pdb.help()"
434 at a prompt.
408 at a prompt.
435
409
436 -p: run program under the control of the Python profiler module (which
410 -p: run program under the control of the Python profiler module (which
437 prints a detailed report of execution times, function calls, etc).
411 prints a detailed report of execution times, function calls, etc).
438
412
439 You can pass other options after -p which affect the behavior of the
413 You can pass other options after -p which affect the behavior of the
440 profiler itself. See the docs for %prun for details.
414 profiler itself. See the docs for %prun for details.
441
415
442 In this mode, the program's variables do NOT propagate back to the
416 In this mode, the program's variables do NOT propagate back to the
443 IPython interactive namespace (because they remain in the namespace
417 IPython interactive namespace (because they remain in the namespace
444 where the profiler executes them).
418 where the profiler executes them).
445
419
446 Internally this triggers a call to %prun, see its documentation for
420 Internally this triggers a call to %prun, see its documentation for
447 details on the options available specifically for profiling.
421 details on the options available specifically for profiling.
448
422
449 There is one special usage for which the text above doesn't apply:
423 There is one special usage for which the text above doesn't apply:
450 if the filename ends with .ipy, the file is run as ipython script,
424 if the filename ends with .ipy, the file is run as ipython script,
451 just as if the commands were written on IPython prompt.
425 just as if the commands were written on IPython prompt.
452
426
453 -m: specify module name to load instead of script path. Similar to
427 -m: specify module name to load instead of script path. Similar to
454 the -m option for the python interpreter. Use this option last if you
428 the -m option for the python interpreter. Use this option last if you
455 want to combine with other %run options. Unlike the python interpreter
429 want to combine with other %run options. Unlike the python interpreter
456 only source modules are allowed no .pyc or .pyo files.
430 only source modules are allowed no .pyc or .pyo files.
457 For example::
431 For example::
458
432
459 %run -m example
433 %run -m example
460
434
461 will run the example module.
435 will run the example module.
462
436
463 -G: disable shell-like glob expansion of arguments.
437 -G: disable shell-like glob expansion of arguments.
464
438
465 """
439 """
466
440
467 # get arguments and set sys.argv for program to be run.
441 # get arguments and set sys.argv for program to be run.
468 opts, arg_lst = self.parse_options(parameter_s,
442 opts, arg_lst = self.parse_options(parameter_s,
469 'nidtN:b:pD:l:rs:T:em:G',
443 'nidtN:b:pD:l:rs:T:em:G',
470 mode='list', list_all=1)
444 mode='list', list_all=1)
471 if "m" in opts:
445 if "m" in opts:
472 modulename = opts["m"][0]
446 modulename = opts["m"][0]
473 modpath = find_mod(modulename)
447 modpath = find_mod(modulename)
474 if modpath is None:
448 if modpath is None:
475 warn('%r is not a valid modulename on sys.path'%modulename)
449 warn('%r is not a valid modulename on sys.path'%modulename)
476 return
450 return
477 arg_lst = [modpath] + arg_lst
451 arg_lst = [modpath] + arg_lst
478 try:
452 try:
479 filename = file_finder(arg_lst[0])
453 filename = file_finder(arg_lst[0])
480 except IndexError:
454 except IndexError:
481 warn('you must provide at least a filename.')
455 warn('you must provide at least a filename.')
482 print '\n%run:\n', oinspect.getdoc(self.run)
456 print '\n%run:\n', oinspect.getdoc(self.run)
483 return
457 return
484 except IOError as e:
458 except IOError as e:
485 try:
459 try:
486 msg = str(e)
460 msg = str(e)
487 except UnicodeError:
461 except UnicodeError:
488 msg = e.message
462 msg = e.message
489 error(msg)
463 error(msg)
490 return
464 return
491
465
492 if filename.lower().endswith('.ipy'):
466 if filename.lower().endswith('.ipy'):
493 with preserve_keys(self.shell.user_ns, '__file__'):
467 with preserve_keys(self.shell.user_ns, '__file__'):
494 self.shell.user_ns['__file__'] = filename
468 self.shell.user_ns['__file__'] = filename
495 self.shell.safe_execfile_ipy(filename)
469 self.shell.safe_execfile_ipy(filename)
496 return
470 return
497
471
498 # Control the response to exit() calls made by the script being run
472 # Control the response to exit() calls made by the script being run
499 exit_ignore = 'e' in opts
473 exit_ignore = 'e' in opts
500
474
501 # Make sure that the running script gets a proper sys.argv as if it
475 # Make sure that the running script gets a proper sys.argv as if it
502 # were run from a system shell.
476 # were run from a system shell.
503 save_argv = sys.argv # save it for later restoring
477 save_argv = sys.argv # save it for later restoring
504
478
505 if 'G' in opts:
479 if 'G' in opts:
506 args = arg_lst[1:]
480 args = arg_lst[1:]
507 else:
481 else:
508 # tilde and glob expansion
482 # tilde and glob expansion
509 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
483 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
510
484
511 sys.argv = [filename] + args # put in the proper filename
485 sys.argv = [filename] + args # put in the proper filename
512 # protect sys.argv from potential unicode strings on Python 2:
486 # protect sys.argv from potential unicode strings on Python 2:
513 if not py3compat.PY3:
487 if not py3compat.PY3:
514 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
488 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
515
489
516 if 'i' in opts:
490 if 'i' in opts:
517 # Run in user's interactive namespace
491 # Run in user's interactive namespace
518 prog_ns = self.shell.user_ns
492 prog_ns = self.shell.user_ns
519 __name__save = self.shell.user_ns['__name__']
493 __name__save = self.shell.user_ns['__name__']
520 prog_ns['__name__'] = '__main__'
494 prog_ns['__name__'] = '__main__'
521 main_mod = self.shell.new_main_mod(prog_ns)
495 main_mod = self.shell.new_main_mod(prog_ns)
522 else:
496 else:
523 # Run in a fresh, empty namespace
497 # Run in a fresh, empty namespace
524 if 'n' in opts:
498 if 'n' in opts:
525 name = os.path.splitext(os.path.basename(filename))[0]
499 name = os.path.splitext(os.path.basename(filename))[0]
526 else:
500 else:
527 name = '__main__'
501 name = '__main__'
528
502
529 main_mod = self.shell.new_main_mod()
503 main_mod = self.shell.new_main_mod()
530 prog_ns = main_mod.__dict__
504 prog_ns = main_mod.__dict__
531 prog_ns['__name__'] = name
505 prog_ns['__name__'] = name
532
506
533 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
507 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
534 # set the __file__ global in the script's namespace
508 # set the __file__ global in the script's namespace
535 prog_ns['__file__'] = filename
509 prog_ns['__file__'] = filename
536
510
537 # pickle fix. See interactiveshell for an explanation. But we need to
511 # pickle fix. See interactiveshell for an explanation. But we need to
538 # make sure that, if we overwrite __main__, we replace it at the end
512 # make sure that, if we overwrite __main__, we replace it at the end
539 main_mod_name = prog_ns['__name__']
513 main_mod_name = prog_ns['__name__']
540
514
541 if main_mod_name == '__main__':
515 if main_mod_name == '__main__':
542 restore_main = sys.modules['__main__']
516 restore_main = sys.modules['__main__']
543 else:
517 else:
544 restore_main = False
518 restore_main = False
545
519
546 # This needs to be undone at the end to prevent holding references to
520 # This needs to be undone at the end to prevent holding references to
547 # every single object ever created.
521 # every single object ever created.
548 sys.modules[main_mod_name] = main_mod
522 sys.modules[main_mod_name] = main_mod
549
523
550 if 'p' in opts or 'd' in opts:
524 if 'p' in opts or 'd' in opts:
551 if 'm' in opts:
525 if 'm' in opts:
552 code = 'run_module(modulename, prog_ns)'
526 code = 'run_module(modulename, prog_ns)'
553 code_ns = {
527 code_ns = {
554 'run_module': self.shell.safe_run_module,
528 'run_module': self.shell.safe_run_module,
555 'prog_ns': prog_ns,
529 'prog_ns': prog_ns,
556 'modulename': modulename,
530 'modulename': modulename,
557 }
531 }
558 else:
532 else:
559 code = 'execfile(filename, prog_ns)'
533 code = 'execfile(filename, prog_ns)'
560 code_ns = {
534 code_ns = {
561 'execfile': self.shell.safe_execfile,
535 'execfile': self.shell.safe_execfile,
562 'prog_ns': prog_ns,
536 'prog_ns': prog_ns,
563 'filename': get_py_filename(filename),
537 'filename': get_py_filename(filename),
564 }
538 }
565
539
566 try:
540 try:
567 stats = None
541 stats = None
568 with self.shell.readline_no_record:
542 with self.shell.readline_no_record:
569 if 'p' in opts:
543 if 'p' in opts:
570 stats = self._run_with_profiler(
544 stats = self._run_with_profiler(code, opts, code_ns)
571 cell=code, user_mode=False, opts=opts,
572 namespace=code_ns)
573 else:
545 else:
574 if 'd' in opts:
546 if 'd' in opts:
575 self._run_with_debugger(
547 self._run_with_debugger(
576 code, code_ns, opts.get('b', ['1'])[0], filename)
548 code, code_ns, opts.get('b', ['1'])[0], filename)
577 else:
549 else:
578 if 'm' in opts:
550 if 'm' in opts:
579 def run():
551 def run():
580 self.shell.safe_run_module(modulename, prog_ns)
552 self.shell.safe_run_module(modulename, prog_ns)
581 else:
553 else:
582 if runner is None:
554 if runner is None:
583 runner = self.default_runner
555 runner = self.default_runner
584 if runner is None:
556 if runner is None:
585 runner = self.shell.safe_execfile
557 runner = self.shell.safe_execfile
586
558
587 def run():
559 def run():
588 runner(filename, prog_ns, prog_ns,
560 runner(filename, prog_ns, prog_ns,
589 exit_ignore=exit_ignore)
561 exit_ignore=exit_ignore)
590
562
591 if 't' in opts:
563 if 't' in opts:
592 # timed execution
564 # timed execution
593 try:
565 try:
594 nruns = int(opts['N'][0])
566 nruns = int(opts['N'][0])
595 if nruns < 1:
567 if nruns < 1:
596 error('Number of runs must be >=1')
568 error('Number of runs must be >=1')
597 return
569 return
598 except (KeyError):
570 except (KeyError):
599 nruns = 1
571 nruns = 1
600 self._run_with_timing(run, nruns)
572 self._run_with_timing(run, nruns)
601 else:
573 else:
602 # regular execution
574 # regular execution
603 run()
575 run()
604
576
605 if 'i' in opts:
577 if 'i' in opts:
606 self.shell.user_ns['__name__'] = __name__save
578 self.shell.user_ns['__name__'] = __name__save
607 else:
579 else:
608 # The shell MUST hold a reference to prog_ns so after %run
580 # The shell MUST hold a reference to prog_ns so after %run
609 # exits, the python deletion mechanism doesn't zero it out
581 # exits, the python deletion mechanism doesn't zero it out
610 # (leaving dangling references).
582 # (leaving dangling references).
611 self.shell.cache_main_mod(prog_ns, filename)
583 self.shell.cache_main_mod(prog_ns, filename)
612 # update IPython interactive namespace
584 # update IPython interactive namespace
613
585
614 # Some forms of read errors on the file may mean the
586 # Some forms of read errors on the file may mean the
615 # __name__ key was never set; using pop we don't have to
587 # __name__ key was never set; using pop we don't have to
616 # worry about a possible KeyError.
588 # worry about a possible KeyError.
617 prog_ns.pop('__name__', None)
589 prog_ns.pop('__name__', None)
618
590
619 with preserve_keys(self.shell.user_ns, '__file__'):
591 with preserve_keys(self.shell.user_ns, '__file__'):
620 self.shell.user_ns.update(prog_ns)
592 self.shell.user_ns.update(prog_ns)
621 finally:
593 finally:
622 # It's a bit of a mystery why, but __builtins__ can change from
594 # It's a bit of a mystery why, but __builtins__ can change from
623 # being a module to becoming a dict missing some key data after
595 # being a module to becoming a dict missing some key data after
624 # %run. As best I can see, this is NOT something IPython is doing
596 # %run. As best I can see, this is NOT something IPython is doing
625 # at all, and similar problems have been reported before:
597 # at all, and similar problems have been reported before:
626 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
598 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
627 # Since this seems to be done by the interpreter itself, the best
599 # Since this seems to be done by the interpreter itself, the best
628 # we can do is to at least restore __builtins__ for the user on
600 # we can do is to at least restore __builtins__ for the user on
629 # exit.
601 # exit.
630 self.shell.user_ns['__builtins__'] = builtin_mod
602 self.shell.user_ns['__builtins__'] = builtin_mod
631
603
632 # Ensure key global structures are restored
604 # Ensure key global structures are restored
633 sys.argv = save_argv
605 sys.argv = save_argv
634 if restore_main:
606 if restore_main:
635 sys.modules['__main__'] = restore_main
607 sys.modules['__main__'] = restore_main
636 else:
608 else:
637 # Remove from sys.modules the reference to main_mod we'd
609 # Remove from sys.modules the reference to main_mod we'd
638 # added. Otherwise it will trap references to objects
610 # added. Otherwise it will trap references to objects
639 # contained therein.
611 # contained therein.
640 del sys.modules[main_mod_name]
612 del sys.modules[main_mod_name]
641
613
642 return stats
614 return stats
643
615
644 def _run_with_debugger(self, code, code_ns, break_point, filename):
616 def _run_with_debugger(self, code, code_ns, break_point, filename):
645 deb = debugger.Pdb(self.shell.colors)
617 deb = debugger.Pdb(self.shell.colors)
646 # reset Breakpoint state, which is moronically kept
618 # reset Breakpoint state, which is moronically kept
647 # in a class
619 # in a class
648 bdb.Breakpoint.next = 1
620 bdb.Breakpoint.next = 1
649 bdb.Breakpoint.bplist = {}
621 bdb.Breakpoint.bplist = {}
650 bdb.Breakpoint.bpbynumber = [None]
622 bdb.Breakpoint.bpbynumber = [None]
651 # Set an initial breakpoint to stop execution
623 # Set an initial breakpoint to stop execution
652 maxtries = 10
624 maxtries = 10
653 bp_file, bp_line = parse_breakpoint(break_point, filename)
625 bp_file, bp_line = parse_breakpoint(break_point, filename)
654 checkline = deb.checkline(bp_file, bp_line)
626 checkline = deb.checkline(bp_file, bp_line)
655 if not checkline:
627 if not checkline:
656 for bp in range(bp_line + 1, bp_line + maxtries + 1):
628 for bp in range(bp_line + 1, bp_line + maxtries + 1):
657 if deb.checkline(bp_file, bp):
629 if deb.checkline(bp_file, bp):
658 break
630 break
659 else:
631 else:
660 msg = ("\nI failed to find a valid line to set "
632 msg = ("\nI failed to find a valid line to set "
661 "a breakpoint\n"
633 "a breakpoint\n"
662 "after trying up to line: %s.\n"
634 "after trying up to line: %s.\n"
663 "Please set a valid breakpoint manually "
635 "Please set a valid breakpoint manually "
664 "with the -b option." % bp)
636 "with the -b option." % bp)
665 error(msg)
637 error(msg)
666 return
638 return
667 # if we find a good linenumber, set the breakpoint
639 # if we find a good linenumber, set the breakpoint
668 deb.do_break('%s:%s' % (bp_file, bp_line))
640 deb.do_break('%s:%s' % (bp_file, bp_line))
669
641
670 # Mimic Pdb._runscript(...)
642 # Mimic Pdb._runscript(...)
671 deb._wait_for_mainpyfile = True
643 deb._wait_for_mainpyfile = True
672 deb.mainpyfile = deb.canonic(filename)
644 deb.mainpyfile = deb.canonic(filename)
673
645
674 # Start file run
646 # Start file run
675 print "NOTE: Enter 'c' at the",
647 print "NOTE: Enter 'c' at the",
676 print "%s prompt to start your script." % deb.prompt
648 print "%s prompt to start your script." % deb.prompt
677 try:
649 try:
678 #save filename so it can be used by methods on the deb object
650 #save filename so it can be used by methods on the deb object
679 deb._exec_filename = filename
651 deb._exec_filename = filename
680 deb.run(code, code_ns)
652 deb.run(code, code_ns)
681
653
682 except:
654 except:
683 etype, value, tb = sys.exc_info()
655 etype, value, tb = sys.exc_info()
684 # Skip three frames in the traceback: the %run one,
656 # Skip three frames in the traceback: the %run one,
685 # one inside bdb.py, and the command-line typed by the
657 # one inside bdb.py, and the command-line typed by the
686 # user (run by exec in pdb itself).
658 # user (run by exec in pdb itself).
687 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
659 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
688
660
689 @staticmethod
661 @staticmethod
690 def _run_with_timing(run, nruns):
662 def _run_with_timing(run, nruns):
691 twall0 = time.time()
663 twall0 = time.time()
692 if nruns == 1:
664 if nruns == 1:
693 t0 = clock2()
665 t0 = clock2()
694 run()
666 run()
695 t1 = clock2()
667 t1 = clock2()
696 t_usr = t1[0] - t0[0]
668 t_usr = t1[0] - t0[0]
697 t_sys = t1[1] - t0[1]
669 t_sys = t1[1] - t0[1]
698 print "\nIPython CPU timings (estimated):"
670 print "\nIPython CPU timings (estimated):"
699 print " User : %10.2f s." % t_usr
671 print " User : %10.2f s." % t_usr
700 print " System : %10.2f s." % t_sys
672 print " System : %10.2f s." % t_sys
701 else:
673 else:
702 runs = range(nruns)
674 runs = range(nruns)
703 t0 = clock2()
675 t0 = clock2()
704 for nr in runs:
676 for nr in runs:
705 run()
677 run()
706 t1 = clock2()
678 t1 = clock2()
707 t_usr = t1[0] - t0[0]
679 t_usr = t1[0] - t0[0]
708 t_sys = t1[1] - t0[1]
680 t_sys = t1[1] - t0[1]
709 print "\nIPython CPU timings (estimated):"
681 print "\nIPython CPU timings (estimated):"
710 print "Total runs performed:", nruns
682 print "Total runs performed:", nruns
711 print " Times : %10s %10s" % ('Total', 'Per run')
683 print " Times : %10s %10s" % ('Total', 'Per run')
712 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
684 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
713 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
685 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
714 twall1 = time.time()
686 twall1 = time.time()
715 print "Wall time: %10.2f s." % (twall1 - twall0)
687 print "Wall time: %10.2f s." % (twall1 - twall0)
716
688
717 @skip_doctest
689 @skip_doctest
718 @line_cell_magic
690 @line_cell_magic
719 def timeit(self, line='', cell=None):
691 def timeit(self, line='', cell=None):
720 """Time execution of a Python statement or expression
692 """Time execution of a Python statement or expression
721
693
722 Usage, in line mode:
694 Usage, in line mode:
723 %timeit [-n<N> -r<R> [-t|-c]] statement
695 %timeit [-n<N> -r<R> [-t|-c]] statement
724 or in cell mode:
696 or in cell mode:
725 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
697 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
726 code
698 code
727 code...
699 code...
728
700
729 Time execution of a Python statement or expression using the timeit
701 Time execution of a Python statement or expression using the timeit
730 module. This function can be used both as a line and cell magic:
702 module. This function can be used both as a line and cell magic:
731
703
732 - In line mode you can time a single-line statement (though multiple
704 - In line mode you can time a single-line statement (though multiple
733 ones can be chained with using semicolons).
705 ones can be chained with using semicolons).
734
706
735 - In cell mode, the statement in the first line is used as setup code
707 - In cell mode, the statement in the first line is used as setup code
736 (executed but not timed) and the body of the cell is timed. The cell
708 (executed but not timed) and the body of the cell is timed. The cell
737 body has access to any variables created in the setup code.
709 body has access to any variables created in the setup code.
738
710
739 Options:
711 Options:
740 -n<N>: execute the given statement <N> times in a loop. If this value
712 -n<N>: execute the given statement <N> times in a loop. If this value
741 is not given, a fitting value is chosen.
713 is not given, a fitting value is chosen.
742
714
743 -r<R>: repeat the loop iteration <R> times and take the best result.
715 -r<R>: repeat the loop iteration <R> times and take the best result.
744 Default: 3
716 Default: 3
745
717
746 -t: use time.time to measure the time, which is the default on Unix.
718 -t: use time.time to measure the time, which is the default on Unix.
747 This function measures wall time.
719 This function measures wall time.
748
720
749 -c: use time.clock to measure the time, which is the default on
721 -c: use time.clock to measure the time, which is the default on
750 Windows and measures wall time. On Unix, resource.getrusage is used
722 Windows and measures wall time. On Unix, resource.getrusage is used
751 instead and returns the CPU user time.
723 instead and returns the CPU user time.
752
724
753 -p<P>: use a precision of <P> digits to display the timing result.
725 -p<P>: use a precision of <P> digits to display the timing result.
754 Default: 3
726 Default: 3
755
727
756
728
757 Examples
729 Examples
758 --------
730 --------
759 ::
731 ::
760
732
761 In [1]: %timeit pass
733 In [1]: %timeit pass
762 10000000 loops, best of 3: 53.3 ns per loop
734 10000000 loops, best of 3: 53.3 ns per loop
763
735
764 In [2]: u = None
736 In [2]: u = None
765
737
766 In [3]: %timeit u is None
738 In [3]: %timeit u is None
767 10000000 loops, best of 3: 184 ns per loop
739 10000000 loops, best of 3: 184 ns per loop
768
740
769 In [4]: %timeit -r 4 u == None
741 In [4]: %timeit -r 4 u == None
770 1000000 loops, best of 4: 242 ns per loop
742 1000000 loops, best of 4: 242 ns per loop
771
743
772 In [5]: import time
744 In [5]: import time
773
745
774 In [6]: %timeit -n1 time.sleep(2)
746 In [6]: %timeit -n1 time.sleep(2)
775 1 loops, best of 3: 2 s per loop
747 1 loops, best of 3: 2 s per loop
776
748
777
749
778 The times reported by %timeit will be slightly higher than those
750 The times reported by %timeit will be slightly higher than those
779 reported by the timeit.py script when variables are accessed. This is
751 reported by the timeit.py script when variables are accessed. This is
780 due to the fact that %timeit executes the statement in the namespace
752 due to the fact that %timeit executes the statement in the namespace
781 of the shell, compared with timeit.py, which uses a single setup
753 of the shell, compared with timeit.py, which uses a single setup
782 statement to import function or create variables. Generally, the bias
754 statement to import function or create variables. Generally, the bias
783 does not matter as long as results from timeit.py are not mixed with
755 does not matter as long as results from timeit.py are not mixed with
784 those from %timeit."""
756 those from %timeit."""
785
757
786 import timeit
758 import timeit
787
759
788 opts, stmt = self.parse_options(line,'n:r:tcp:',
760 opts, stmt = self.parse_options(line,'n:r:tcp:',
789 posix=False, strict=False)
761 posix=False, strict=False)
790 if stmt == "" and cell is None:
762 if stmt == "" and cell is None:
791 return
763 return
792
764
793 timefunc = timeit.default_timer
765 timefunc = timeit.default_timer
794 number = int(getattr(opts, "n", 0))
766 number = int(getattr(opts, "n", 0))
795 repeat = int(getattr(opts, "r", timeit.default_repeat))
767 repeat = int(getattr(opts, "r", timeit.default_repeat))
796 precision = int(getattr(opts, "p", 3))
768 precision = int(getattr(opts, "p", 3))
797 if hasattr(opts, "t"):
769 if hasattr(opts, "t"):
798 timefunc = time.time
770 timefunc = time.time
799 if hasattr(opts, "c"):
771 if hasattr(opts, "c"):
800 timefunc = clock
772 timefunc = clock
801
773
802 timer = timeit.Timer(timer=timefunc)
774 timer = timeit.Timer(timer=timefunc)
803 # this code has tight coupling to the inner workings of timeit.Timer,
775 # this code has tight coupling to the inner workings of timeit.Timer,
804 # but is there a better way to achieve that the code stmt has access
776 # but is there a better way to achieve that the code stmt has access
805 # to the shell namespace?
777 # to the shell namespace?
806 transform = self.shell.input_splitter.transform_cell
778 transform = self.shell.input_splitter.transform_cell
807
779
808 if cell is None:
780 if cell is None:
809 # called as line magic
781 # called as line magic
810 ast_setup = ast.parse("pass")
782 ast_setup = ast.parse("pass")
811 ast_stmt = ast.parse(transform(stmt))
783 ast_stmt = ast.parse(transform(stmt))
812 else:
784 else:
813 ast_setup = ast.parse(transform(stmt))
785 ast_setup = ast.parse(transform(stmt))
814 ast_stmt = ast.parse(transform(cell))
786 ast_stmt = ast.parse(transform(cell))
815
787
816 ast_setup = self.shell.transform_ast(ast_setup)
788 ast_setup = self.shell.transform_ast(ast_setup)
817 ast_stmt = self.shell.transform_ast(ast_stmt)
789 ast_stmt = self.shell.transform_ast(ast_stmt)
818
790
819 # This codestring is taken from timeit.template - we fill it in as an
791 # This codestring is taken from timeit.template - we fill it in as an
820 # AST, so that we can apply our AST transformations to the user code
792 # AST, so that we can apply our AST transformations to the user code
821 # without affecting the timing code.
793 # without affecting the timing code.
822 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
794 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
823 ' setup\n'
795 ' setup\n'
824 ' _t0 = _timer()\n'
796 ' _t0 = _timer()\n'
825 ' for _i in _it:\n'
797 ' for _i in _it:\n'
826 ' stmt\n'
798 ' stmt\n'
827 ' _t1 = _timer()\n'
799 ' _t1 = _timer()\n'
828 ' return _t1 - _t0\n')
800 ' return _t1 - _t0\n')
829
801
830 class TimeitTemplateFiller(ast.NodeTransformer):
802 class TimeitTemplateFiller(ast.NodeTransformer):
831 "This is quite tightly tied to the template definition above."
803 "This is quite tightly tied to the template definition above."
832 def visit_FunctionDef(self, node):
804 def visit_FunctionDef(self, node):
833 "Fill in the setup statement"
805 "Fill in the setup statement"
834 self.generic_visit(node)
806 self.generic_visit(node)
835 if node.name == "inner":
807 if node.name == "inner":
836 node.body[:1] = ast_setup.body
808 node.body[:1] = ast_setup.body
837
809
838 return node
810 return node
839
811
840 def visit_For(self, node):
812 def visit_For(self, node):
841 "Fill in the statement to be timed"
813 "Fill in the statement to be timed"
842 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
814 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
843 node.body = ast_stmt.body
815 node.body = ast_stmt.body
844 return node
816 return node
845
817
846 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
818 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
847 timeit_ast = ast.fix_missing_locations(timeit_ast)
819 timeit_ast = ast.fix_missing_locations(timeit_ast)
848
820
849 # Track compilation time so it can be reported if too long
821 # Track compilation time so it can be reported if too long
850 # Minimum time above which compilation time will be reported
822 # Minimum time above which compilation time will be reported
851 tc_min = 0.1
823 tc_min = 0.1
852
824
853 t0 = clock()
825 t0 = clock()
854 code = compile(timeit_ast, "<magic-timeit>", "exec")
826 code = compile(timeit_ast, "<magic-timeit>", "exec")
855 tc = clock()-t0
827 tc = clock()-t0
856
828
857 ns = {}
829 ns = {}
858 exec code in self.shell.user_ns, ns
830 exec code in self.shell.user_ns, ns
859 timer.inner = ns["inner"]
831 timer.inner = ns["inner"]
860
832
861 if number == 0:
833 if number == 0:
862 # determine number so that 0.2 <= total time < 2.0
834 # determine number so that 0.2 <= total time < 2.0
863 number = 1
835 number = 1
864 for i in range(1, 10):
836 for i in range(1, 10):
865 if timer.timeit(number) >= 0.2:
837 if timer.timeit(number) >= 0.2:
866 break
838 break
867 number *= 10
839 number *= 10
868
840
869 best = min(timer.repeat(repeat, number)) / number
841 best = min(timer.repeat(repeat, number)) / number
870
842
871 print u"%d loops, best of %d: %s per loop" % (number, repeat,
843 print u"%d loops, best of %d: %s per loop" % (number, repeat,
872 _format_time(best, precision))
844 _format_time(best, precision))
873 if tc > tc_min:
845 if tc > tc_min:
874 print "Compiler time: %.2f s" % tc
846 print "Compiler time: %.2f s" % tc
875
847
876 @skip_doctest
848 @skip_doctest
877 @needs_local_scope
849 @needs_local_scope
878 @line_cell_magic
850 @line_cell_magic
879 def time(self,line='', cell=None, local_ns=None):
851 def time(self,line='', cell=None, local_ns=None):
880 """Time execution of a Python statement or expression.
852 """Time execution of a Python statement or expression.
881
853
882 The CPU and wall clock times are printed, and the value of the
854 The CPU and wall clock times are printed, and the value of the
883 expression (if any) is returned. Note that under Win32, system time
855 expression (if any) is returned. Note that under Win32, system time
884 is always reported as 0, since it can not be measured.
856 is always reported as 0, since it can not be measured.
885
857
886 This function can be used both as a line and cell magic:
858 This function can be used both as a line and cell magic:
887
859
888 - In line mode you can time a single-line statement (though multiple
860 - In line mode you can time a single-line statement (though multiple
889 ones can be chained with using semicolons).
861 ones can be chained with using semicolons).
890
862
891 - In cell mode, you can time the cell body (a directly
863 - In cell mode, you can time the cell body (a directly
892 following statement raises an error).
864 following statement raises an error).
893
865
894 This function provides very basic timing functionality. Use the timeit
866 This function provides very basic timing functionality. Use the timeit
895 magic for more controll over the measurement.
867 magic for more controll over the measurement.
896
868
897 Examples
869 Examples
898 --------
870 --------
899 ::
871 ::
900
872
901 In [1]: %time 2**128
873 In [1]: %time 2**128
902 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
874 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
903 Wall time: 0.00
875 Wall time: 0.00
904 Out[1]: 340282366920938463463374607431768211456L
876 Out[1]: 340282366920938463463374607431768211456L
905
877
906 In [2]: n = 1000000
878 In [2]: n = 1000000
907
879
908 In [3]: %time sum(range(n))
880 In [3]: %time sum(range(n))
909 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
881 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
910 Wall time: 1.37
882 Wall time: 1.37
911 Out[3]: 499999500000L
883 Out[3]: 499999500000L
912
884
913 In [4]: %time print 'hello world'
885 In [4]: %time print 'hello world'
914 hello world
886 hello world
915 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
887 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
916 Wall time: 0.00
888 Wall time: 0.00
917
889
918 Note that the time needed by Python to compile the given expression
890 Note that the time needed by Python to compile the given expression
919 will be reported if it is more than 0.1s. In this example, the
891 will be reported if it is more than 0.1s. In this example, the
920 actual exponentiation is done by Python at compilation time, so while
892 actual exponentiation is done by Python at compilation time, so while
921 the expression can take a noticeable amount of time to compute, that
893 the expression can take a noticeable amount of time to compute, that
922 time is purely due to the compilation:
894 time is purely due to the compilation:
923
895
924 In [5]: %time 3**9999;
896 In [5]: %time 3**9999;
925 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
897 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
926 Wall time: 0.00 s
898 Wall time: 0.00 s
927
899
928 In [6]: %time 3**999999;
900 In [6]: %time 3**999999;
929 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
901 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
930 Wall time: 0.00 s
902 Wall time: 0.00 s
931 Compiler : 0.78 s
903 Compiler : 0.78 s
932 """
904 """
933
905
934 # fail immediately if the given expression can't be compiled
906 # fail immediately if the given expression can't be compiled
935
907
936 if line and cell:
908 if line and cell:
937 raise UsageError("Can't use statement directly after '%%time'!")
909 raise UsageError("Can't use statement directly after '%%time'!")
938
910
939 if cell:
911 if cell:
940 expr = self.shell.prefilter(cell,False)
912 expr = self.shell.prefilter(cell,False)
941 else:
913 else:
942 expr = self.shell.prefilter(line,False)
914 expr = self.shell.prefilter(line,False)
943
915
944 # Minimum time above which parse time will be reported
916 # Minimum time above which parse time will be reported
945 tp_min = 0.1
917 tp_min = 0.1
946
918
947 t0 = clock()
919 t0 = clock()
948 expr_ast = ast.parse(expr)
920 expr_ast = ast.parse(expr)
949 tp = clock()-t0
921 tp = clock()-t0
950
922
951 # Apply AST transformations
923 # Apply AST transformations
952 expr_ast = self.shell.transform_ast(expr_ast)
924 expr_ast = self.shell.transform_ast(expr_ast)
953
925
954 # Minimum time above which compilation time will be reported
926 # Minimum time above which compilation time will be reported
955 tc_min = 0.1
927 tc_min = 0.1
956
928
957 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
929 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
958 mode = 'eval'
930 mode = 'eval'
959 source = '<timed eval>'
931 source = '<timed eval>'
960 expr_ast = ast.Expression(expr_ast.body[0].value)
932 expr_ast = ast.Expression(expr_ast.body[0].value)
961 else:
933 else:
962 mode = 'exec'
934 mode = 'exec'
963 source = '<timed exec>'
935 source = '<timed exec>'
964 t0 = clock()
936 t0 = clock()
965 code = compile(expr_ast, source, mode)
937 code = compile(expr_ast, source, mode)
966 tc = clock()-t0
938 tc = clock()-t0
967
939
968 # skew measurement as little as possible
940 # skew measurement as little as possible
969 glob = self.shell.user_ns
941 glob = self.shell.user_ns
970 wtime = time.time
942 wtime = time.time
971 # time execution
943 # time execution
972 wall_st = wtime()
944 wall_st = wtime()
973 if mode=='eval':
945 if mode=='eval':
974 st = clock2()
946 st = clock2()
975 out = eval(code, glob, local_ns)
947 out = eval(code, glob, local_ns)
976 end = clock2()
948 end = clock2()
977 else:
949 else:
978 st = clock2()
950 st = clock2()
979 exec code in glob, local_ns
951 exec code in glob, local_ns
980 end = clock2()
952 end = clock2()
981 out = None
953 out = None
982 wall_end = wtime()
954 wall_end = wtime()
983 # Compute actual times and report
955 # Compute actual times and report
984 wall_time = wall_end-wall_st
956 wall_time = wall_end-wall_st
985 cpu_user = end[0]-st[0]
957 cpu_user = end[0]-st[0]
986 cpu_sys = end[1]-st[1]
958 cpu_sys = end[1]-st[1]
987 cpu_tot = cpu_user+cpu_sys
959 cpu_tot = cpu_user+cpu_sys
988 # On windows cpu_sys is always zero, so no new information to the next print
960 # On windows cpu_sys is always zero, so no new information to the next print
989 if sys.platform != 'win32':
961 if sys.platform != 'win32':
990 print "CPU times: user %s, sys: %s, total: %s" % \
962 print "CPU times: user %s, sys: %s, total: %s" % \
991 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))
963 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))
992 print "Wall time: %s" % _format_time(wall_time)
964 print "Wall time: %s" % _format_time(wall_time)
993 if tc > tc_min:
965 if tc > tc_min:
994 print "Compiler : %s" % _format_time(tc)
966 print "Compiler : %s" % _format_time(tc)
995 if tp > tp_min:
967 if tp > tp_min:
996 print "Parser : %s" % _format_time(tp)
968 print "Parser : %s" % _format_time(tp)
997 return out
969 return out
998
970
999 @skip_doctest
971 @skip_doctest
1000 @line_magic
972 @line_magic
1001 def macro(self, parameter_s=''):
973 def macro(self, parameter_s=''):
1002 """Define a macro for future re-execution. It accepts ranges of history,
974 """Define a macro for future re-execution. It accepts ranges of history,
1003 filenames or string objects.
975 filenames or string objects.
1004
976
1005 Usage:\\
977 Usage:\\
1006 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
978 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1007
979
1008 Options:
980 Options:
1009
981
1010 -r: use 'raw' input. By default, the 'processed' history is used,
982 -r: use 'raw' input. By default, the 'processed' history is used,
1011 so that magics are loaded in their transformed version to valid
983 so that magics are loaded in their transformed version to valid
1012 Python. If this option is given, the raw input as typed as the
984 Python. If this option is given, the raw input as typed as the
1013 command line is used instead.
985 command line is used instead.
1014
986
1015 This will define a global variable called `name` which is a string
987 This will define a global variable called `name` which is a string
1016 made of joining the slices and lines you specify (n1,n2,... numbers
988 made of joining the slices and lines you specify (n1,n2,... numbers
1017 above) from your input history into a single string. This variable
989 above) from your input history into a single string. This variable
1018 acts like an automatic function which re-executes those lines as if
990 acts like an automatic function which re-executes those lines as if
1019 you had typed them. You just type 'name' at the prompt and the code
991 you had typed them. You just type 'name' at the prompt and the code
1020 executes.
992 executes.
1021
993
1022 The syntax for indicating input ranges is described in %history.
994 The syntax for indicating input ranges is described in %history.
1023
995
1024 Note: as a 'hidden' feature, you can also use traditional python slice
996 Note: as a 'hidden' feature, you can also use traditional python slice
1025 notation, where N:M means numbers N through M-1.
997 notation, where N:M means numbers N through M-1.
1026
998
1027 For example, if your history contains (%hist prints it)::
999 For example, if your history contains (%hist prints it)::
1028
1000
1029 44: x=1
1001 44: x=1
1030 45: y=3
1002 45: y=3
1031 46: z=x+y
1003 46: z=x+y
1032 47: print x
1004 47: print x
1033 48: a=5
1005 48: a=5
1034 49: print 'x',x,'y',y
1006 49: print 'x',x,'y',y
1035
1007
1036 you can create a macro with lines 44 through 47 (included) and line 49
1008 you can create a macro with lines 44 through 47 (included) and line 49
1037 called my_macro with::
1009 called my_macro with::
1038
1010
1039 In [55]: %macro my_macro 44-47 49
1011 In [55]: %macro my_macro 44-47 49
1040
1012
1041 Now, typing `my_macro` (without quotes) will re-execute all this code
1013 Now, typing `my_macro` (without quotes) will re-execute all this code
1042 in one pass.
1014 in one pass.
1043
1015
1044 You don't need to give the line-numbers in order, and any given line
1016 You don't need to give the line-numbers in order, and any given line
1045 number can appear multiple times. You can assemble macros with any
1017 number can appear multiple times. You can assemble macros with any
1046 lines from your input history in any order.
1018 lines from your input history in any order.
1047
1019
1048 The macro is a simple object which holds its value in an attribute,
1020 The macro is a simple object which holds its value in an attribute,
1049 but IPython's display system checks for macros and executes them as
1021 but IPython's display system checks for macros and executes them as
1050 code instead of printing them when you type their name.
1022 code instead of printing them when you type their name.
1051
1023
1052 You can view a macro's contents by explicitly printing it with::
1024 You can view a macro's contents by explicitly printing it with::
1053
1025
1054 print macro_name
1026 print macro_name
1055
1027
1056 """
1028 """
1057 opts,args = self.parse_options(parameter_s,'r',mode='list')
1029 opts,args = self.parse_options(parameter_s,'r',mode='list')
1058 if not args: # List existing macros
1030 if not args: # List existing macros
1059 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1031 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1060 isinstance(v, Macro))
1032 isinstance(v, Macro))
1061 if len(args) == 1:
1033 if len(args) == 1:
1062 raise UsageError(
1034 raise UsageError(
1063 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1035 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1064 name, codefrom = args[0], " ".join(args[1:])
1036 name, codefrom = args[0], " ".join(args[1:])
1065
1037
1066 #print 'rng',ranges # dbg
1038 #print 'rng',ranges # dbg
1067 try:
1039 try:
1068 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1040 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1069 except (ValueError, TypeError) as e:
1041 except (ValueError, TypeError) as e:
1070 print e.args[0]
1042 print e.args[0]
1071 return
1043 return
1072 macro = Macro(lines)
1044 macro = Macro(lines)
1073 self.shell.define_macro(name, macro)
1045 self.shell.define_macro(name, macro)
1074 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1046 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1075 print '=== Macro contents: ==='
1047 print '=== Macro contents: ==='
1076 print macro,
1048 print macro,
1077
1049
1078 @magic_arguments.magic_arguments()
1050 @magic_arguments.magic_arguments()
1079 @magic_arguments.argument('output', type=str, default='', nargs='?',
1051 @magic_arguments.argument('output', type=str, default='', nargs='?',
1080 help="""The name of the variable in which to store output.
1052 help="""The name of the variable in which to store output.
1081 This is a utils.io.CapturedIO object with stdout/err attributes
1053 This is a utils.io.CapturedIO object with stdout/err attributes
1082 for the text of the captured output.
1054 for the text of the captured output.
1083
1055
1084 CapturedOutput also has a show() method for displaying the output,
1056 CapturedOutput also has a show() method for displaying the output,
1085 and __call__ as well, so you can use that to quickly display the
1057 and __call__ as well, so you can use that to quickly display the
1086 output.
1058 output.
1087
1059
1088 If unspecified, captured output is discarded.
1060 If unspecified, captured output is discarded.
1089 """
1061 """
1090 )
1062 )
1091 @magic_arguments.argument('--no-stderr', action="store_true",
1063 @magic_arguments.argument('--no-stderr', action="store_true",
1092 help="""Don't capture stderr."""
1064 help="""Don't capture stderr."""
1093 )
1065 )
1094 @magic_arguments.argument('--no-stdout', action="store_true",
1066 @magic_arguments.argument('--no-stdout', action="store_true",
1095 help="""Don't capture stdout."""
1067 help="""Don't capture stdout."""
1096 )
1068 )
1097 @cell_magic
1069 @cell_magic
1098 def capture(self, line, cell):
1070 def capture(self, line, cell):
1099 """run the cell, capturing stdout/err"""
1071 """run the cell, capturing stdout/err"""
1100 args = magic_arguments.parse_argstring(self.capture, line)
1072 args = magic_arguments.parse_argstring(self.capture, line)
1101 out = not args.no_stdout
1073 out = not args.no_stdout
1102 err = not args.no_stderr
1074 err = not args.no_stderr
1103 with capture_output(out, err) as io:
1075 with capture_output(out, err) as io:
1104 self.shell.run_cell(cell)
1076 self.shell.run_cell(cell)
1105 if args.output:
1077 if args.output:
1106 self.shell.user_ns[args.output] = io
1078 self.shell.user_ns[args.output] = io
1107
1079
1108 def parse_breakpoint(text, current_file):
1080 def parse_breakpoint(text, current_file):
1109 '''Returns (file, line) for file:line and (current_file, line) for line'''
1081 '''Returns (file, line) for file:line and (current_file, line) for line'''
1110 colon = text.find(':')
1082 colon = text.find(':')
1111 if colon == -1:
1083 if colon == -1:
1112 return current_file, int(text)
1084 return current_file, int(text)
1113 else:
1085 else:
1114 return text[:colon], int(text[colon+1:])
1086 return text[:colon], int(text[colon+1:])
1115
1087
1116 def _format_time(timespan, precision=3):
1088 def _format_time(timespan, precision=3):
1117 """Formats the timespan in a human readable form"""
1089 """Formats the timespan in a human readable form"""
1118 import math
1090 import math
1119
1091
1120 if timespan >= 60.0:
1092 if timespan >= 60.0:
1121 # we have more than a minute, format that in a human readable form
1093 # we have more than a minute, format that in a human readable form
1122 # Idea from http://snipplr.com/view/5713/
1094 # Idea from http://snipplr.com/view/5713/
1123 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1095 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1124 time = []
1096 time = []
1125 leftover = timespan
1097 leftover = timespan
1126 for suffix, length in parts:
1098 for suffix, length in parts:
1127 value = int(leftover / length)
1099 value = int(leftover / length)
1128 if value > 0:
1100 if value > 0:
1129 leftover = leftover % length
1101 leftover = leftover % length
1130 time.append(u'%s%s' % (str(value), suffix))
1102 time.append(u'%s%s' % (str(value), suffix))
1131 if leftover < 1:
1103 if leftover < 1:
1132 break
1104 break
1133 return " ".join(time)
1105 return " ".join(time)
1134
1106
1135
1107
1136 # Unfortunately the unicode 'micro' symbol can cause problems in
1108 # Unfortunately the unicode 'micro' symbol can cause problems in
1137 # certain terminals.
1109 # certain terminals.
1138 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1110 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1139 # Try to prevent crashes by being more secure than it needs to
1111 # Try to prevent crashes by being more secure than it needs to
1140 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1112 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1141 units = [u"s", u"ms",u'us',"ns"] # the save value
1113 units = [u"s", u"ms",u'us',"ns"] # the save value
1142 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1114 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1143 try:
1115 try:
1144 u'\xb5'.encode(sys.stdout.encoding)
1116 u'\xb5'.encode(sys.stdout.encoding)
1145 units = [u"s", u"ms",u'\xb5s',"ns"]
1117 units = [u"s", u"ms",u'\xb5s',"ns"]
1146 except:
1118 except:
1147 pass
1119 pass
1148 scaling = [1, 1e3, 1e6, 1e9]
1120 scaling = [1, 1e3, 1e6, 1e9]
1149
1121
1150 if timespan > 0.0:
1122 if timespan > 0.0:
1151 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1123 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1152 else:
1124 else:
1153 order = 3
1125 order = 3
1154 ret = u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1126 ret = u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1155 return ret
1127 return ret
General Comments 0
You need to be logged in to leave comments. Login now