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