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