##// END OF EJS Templates
Make %time magic work with AST transformations
Thomas Kluyver -
Show More
@@ -892,20 +892,31 b' python-profiler package from non-free.""")'
892 892 # fail immediately if the given expression can't be compiled
893 893
894 894 expr = self.shell.prefilter(parameter_s,False)
895
896 # Minimum time above which parse time will be reported
897 tp_min = 0.1
898
899 t0 = clock()
900 expr_ast = ast.parse(expr)
901 tp = clock()-t0
902
903 # Apply AST transformations
904 expr_ast = self.shell.transform_ast(expr_ast)
895 905
896 906 # Minimum time above which compilation time will be reported
897 907 tc_min = 0.1
898 908
899 try:
909 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
900 910 mode = 'eval'
901 t0 = clock()
902 code = compile(expr,'<timed eval>',mode)
903 tc = clock()-t0
904 except SyntaxError:
911 source = '<timed eval>'
912 expr_ast = ast.Expression(expr_ast.body[0].value)
913 else:
905 914 mode = 'exec'
906 t0 = clock()
907 code = compile(expr,'<timed exec>',mode)
908 tc = clock()-t0
915 source = '<timed exec>'
916 t0 = clock()
917 code = compile(expr_ast, source, mode)
918 tc = clock()-t0
919
909 920 # skew measurement as little as possible
910 921 glob = self.shell.user_ns
911 922 wtime = time.time
@@ -931,6 +942,8 b' python-profiler package from non-free.""")'
931 942 print "Wall time: %.2f s" % wall_time
932 943 if tc > tc_min:
933 944 print "Compiler : %.2f s" % tc
945 if tp > tp_min:
946 print "Parser : %.2f s" % tp
934 947 return out
935 948
936 949 @skip_doctest
@@ -452,6 +452,23 b' class TestAstTransform(unittest.TestCase):'
452 452 with tt.AssertPrints("best of "):
453 453 ip.run_cell_magic("timeit", "-n1 f(2)", "f(3)")
454 454 self.assertEqual(called, set([-2, -3]))
455
456 def test_time(self):
457 called = []
458 def f(x):
459 called.append(x)
460 ip.push({'f':f})
461
462 # Test with an expression
463 with tt.AssertPrints("CPU times"):
464 ip.run_line_magic("time", "f(5+9)")
465 self.assertEqual(called, [-14])
466 called[:] = []
467
468 # Test with a statement (different code path)
469 with tt.AssertPrints("CPU times"):
470 ip.run_line_magic("time", "a = f(-3 + -2)")
471 self.assertEqual(called, [5])
455 472
456 473 class IntegerWrapper(ast.NodeTransformer):
457 474 """Wraps all integers in a call to Integer()"""
General Comments 0
You need to be logged in to leave comments. Login now