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