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