[16/24] +-Infinity: correct assumptions
[sympy.git] / bin / sympy_time_cache.py
blobd27c96e1c54e0f966a047a15f2ed0d5efca40ff5
1 import time, timeit
3 class TreeNode(object):
4 def __init__(self, name):
5 self._name = name
6 self._children = []
7 self._time = 0
9 def __str__(self):
10 return "%s: %s"%(self._name, self._time)
12 __repr__ = __str__
14 def add_child(self, node):
15 self._children.append(node)
17 def children(self):
18 return self._children
20 def child(self, i):
21 return self.children()[i]
23 def set_time(self, time):
24 self._time = time
26 def time(self):
27 return self._time
29 total_time = time
31 def exclusive_time(self):
32 return self.total_time() - sum(child.time() for child in self.children())
34 def name(self):
35 return self._name
37 def linearize(self):
38 res = [self]
39 for child in self.children():
40 res.extend(child.linearize())
41 return res
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:
46 return
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):
63 f = open(f, "w")
64 f.write("events: Microseconds\n")
65 f.write("fl=sympyallimport\n")
66 must_close = True
67 else:
68 must_close = False
70 f.write("fn=%s\n"%self.name())
71 f.write("1 %s\n"%self.exclusive_time())
73 counter = 2
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()))
78 counter += 1
80 f.write("\n\n")
82 for child in self.children():
83 child.write_cachegrind(f)
85 if must_close:
86 f.close()
89 pp = TreeNode(None) #We have to use pp since there is a sage function
90 #called parent that gets imported
91 seen = set()
93 def new_import(name, globals={}, locals={}, fromlist=[]):
94 global pp
95 if name in seen:
96 return old_import(name, globals, locals, fromlist)
97 seen.add(name)
99 node = TreeNode(name)
101 pp.add_child(node)
102 old_pp = pp
103 pp = node
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)))
112 pp = old_pp
114 return module
116 old_import = __builtins__.__import__
118 __builtins__.__import__ = new_import
119 old_sum = sum
121 from sympy import *
123 sum = old_sum
125 sageall = pp.child(0)
126 sageall.write_cachegrind("sympy.cachegrind")
128 print "Timings saved. Do:\n$ kcachegrind sympy.cachegrind"