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