1
# this is copied from the lsprof distro because somehow
2
# it is not installed by distutils
3
# I made one modification to profile so that it returns a pair
4
# instead of just the Stats object
7
from _lsprof import Profiler, profiler_entry
9
__all__ = ['profile', 'Stats']
11
def profile(f, *args, **kwds):
14
p.enable(subcalls=True)
16
ret = f(*args, **kwds)
19
return ret,Stats(p.getstats())
25
def __init__(self, data):
28
def sort(self, crit="inlinetime"):
30
if crit not in profiler_entry.__dict__:
31
raise ValueError, "Can't sort by %s" % crit
32
self.data.sort(lambda b, a: cmp(getattr(a, crit),
36
e.calls.sort(lambda b, a: cmp(getattr(a, crit),
39
def pprint(self, top=None, file=None):
46
cols = "% 12s %12s %11.4f %11.4f %s\n"
47
hcols = "% 12s %12s %12s %12s %s\n"
48
cols2 = "+%12s %12s %11.4f %11.4f + %s\n"
49
file.write(hcols % ("CallCount", "Recursive", "Total(ms)",
50
"Inline(ms)", "module:lineno(function)"))
52
file.write(cols % (e.callcount, e.reccallcount, e.totaltime,
53
e.inlinetime, label(e.code)))
56
file.write(cols % ("+%s" % se.callcount, se.reccallcount,
57
se.totaltime, se.inlinetime,
58
"+%s" % label(se.code)))
61
"""Replace all references to code objects with string
62
descriptions; this makes it possible to pickle the instance."""
64
# this code is probably rather ickier than it needs to be!
65
for i in range(len(self.data)):
67
if not isinstance(e.code, str):
68
self.data[i] = type(e)((label(e.code),) + e[1:])
70
for j in range(len(e.calls)):
72
if not isinstance(se.code, str):
73
e.calls[j] = type(se)((label(se.code),) + se[1:])
78
if isinstance(code, str):
81
mname = _fn2mod[code.co_filename]
83
for k, v in sys.modules.iteritems():
86
if not hasattr(v, '__file__'):
88
if not isinstance(v.__file__, str):
90
if v.__file__.startswith(code.co_filename):
91
mname = _fn2mod[code.co_filename] = k
94
mname = _fn2mod[code.co_filename] = '<%s>'%code.co_filename
96
return '%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name)
99
if __name__ == '__main__':
101
sys.argv = sys.argv[1:]
103
print >> sys.stderr, "usage: lsprof.py <script> <arguments...>"
105
sys.path.insert(0, os.path.abspath(os.path.dirname(sys.argv[0])))
106
stats = profile(execfile, sys.argv[0], globals(), locals())