3 class TreeNode(object):
4 def __init__(self
, name
):
10 return "%s: %s"%(self
._name
, self
._time
)
14 def add_child(self
, node
):
15 self
._children
.append(node
)
21 return self
.children()[i
]
23 def set_time(self
, time
):
31 def exclusive_time(self
):
32 return self
.total_time() - sum(child
.time() for child
in self
.children())
39 for child
in self
.children():
40 res
.extend(child
.linearize())
43 def print_tree(self
, level
=0, max_depth
=None):
44 print " "*level
+ str(self
)
45 if max_depth
is not None and max_depth
<= level
:
47 for child
in self
.children():
48 child
.print_tree(level
+1, max_depth
=max_depth
)
50 def print_generic(self
, n
=50, method
="time"):
51 slowest
= sorted((getattr(node
, method
)(), node
.name()) for node
in self
.linearize())[-n
:]
52 for time
, name
in slowest
[::-1]:
53 print "%s %s"%(time
, name
)
55 def print_slowest(self
, n
=50):
56 self
.print_generic(n
=50, method
="time")
58 def print_slowest_exclusive(self
, n
=50):
59 self
.print_generic(n
, method
="exclusive_time")
61 def write_cachegrind(self
, f
):
62 if isinstance(f
, str):
64 f
.write("events: Microseconds\n")
65 f
.write("fl=sympyallimport\n")
70 f
.write("fn=%s\n"%self
.name())
71 f
.write("1 %s\n"%self
.exclusive_time())
74 for child
in self
.children():
75 f
.write("cfn=%s\n"%child
.name())
76 f
.write("calls=1 1\n")
77 f
.write("%s %s\n"%(counter
, child
.time()))
82 for child
in self
.children():
83 child
.write_cachegrind(f
)
89 pp
= TreeNode(None) #We have to use pp since there is a sage function
90 #called parent that gets imported
93 def new_import(name
, globals={}, locals={}, fromlist
=[]):
96 return old_import(name
, globals, locals, fromlist
)
105 #Do the actual import
106 t1
= timeit
.default_timer()
107 module
= old_import(name
, globals, locals, fromlist
)
108 t2
= timeit
.default_timer()
109 node
.set_time(int(1000000*(t2
-t1
)))
116 old_import
= __builtins__
.__import
__
118 __builtins__
.__import
__ = new_import
125 sageall
= pp
.child(0)
126 sageall
.write_cachegrind("sympy.cachegrind")
128 print "Timings saved. Do:\n$ kcachegrind sympy.cachegrind"