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
 
 
9
from _lsprof import Profiler, profiler_entry
 
 
11
__all__ = ['profile', 'Stats']
 
 
16
def _thread_profile(f, *args, **kwds):
 
 
17
    # we lose the first profile point for a new thread in order to trampoline
 
 
18
    # a new Profile object into place
 
 
20
    thr = thread.get_ident()
 
 
21
    _g_threadmap[thr] = p = Profiler()
 
 
22
    # this overrides our sys.setprofile hook:
 
 
23
    p.enable(subcalls=True, builtins=True)
 
 
26
def profile(f, *args, **kwds):
 
 
30
    p.enable(subcalls=True)
 
 
31
    threading.setprofile(_thread_profile)
 
 
33
        ret = f(*args, **kwds)
 
 
36
        for pp in _g_threadmap.values():
 
 
38
        threading.setprofile(None)
 
 
41
    for tid, pp in _g_threadmap.items():
 
 
42
        threads[tid] = Stats(pp.getstats(), {})
 
 
44
    return ret, Stats(p.getstats(), threads)
 
 
50
    def __init__(self, data, threads):
 
 
52
        self.threads = threads
 
 
54
    def sort(self, crit="inlinetime"):
 
 
56
        if crit not in profiler_entry.__dict__:
 
 
57
            raise ValueError, "Can't sort by %s" % crit
 
 
58
        self.data.sort(lambda b, a: cmp(getattr(a, crit),
 
 
62
                e.calls.sort(lambda b, a: cmp(getattr(a, crit),
 
 
65
    def pprint(self, top=None, file=None):
 
 
72
        cols = "% 12s %12s %11.4f %11.4f   %s\n"
 
 
73
        hcols = "% 12s %12s %12s %12s %s\n"
 
 
74
        cols2 = "+%12s %12s %11.4f %11.4f +  %s\n"
 
 
75
        file.write(hcols % ("CallCount", "Recursive", "Total(ms)",
 
 
76
                            "Inline(ms)", "module:lineno(function)"))
 
 
78
            file.write(cols % (e.callcount, e.reccallcount, e.totaltime,
 
 
79
                               e.inlinetime, label(e.code)))
 
 
82
                    file.write(cols % ("+%s" % se.callcount, se.reccallcount,
 
 
83
                                       se.totaltime, se.inlinetime,
 
 
84
                                       "+%s" % label(se.code)))
 
 
87
        """Replace all references to code objects with string
 
 
88
        descriptions; this makes it possible to pickle the instance."""
 
 
90
        # this code is probably rather ickier than it needs to be!
 
 
91
        for i in range(len(self.data)):
 
 
93
            if not isinstance(e.code, str):
 
 
94
                self.data[i] = type(e)((label(e.code),) + e[1:])
 
 
96
                for j in range(len(e.calls)):
 
 
98
                    if not isinstance(se.code, str):
 
 
99
                        e.calls[j] = type(se)((label(se.code),) + se[1:])
 
 
100
        for s in self.threads.values():
 
 
103
    def calltree(self, file):
 
 
104
        """Output profiling data in calltree format (for KCacheGrind)."""
 
 
105
        _CallTreeFilter(self.data).output(file)
 
 
108
class _CallTreeFilter(object):
 
 
110
    def __init__(self, data):
 
 
114
    def output(self, out_file):
 
 
115
        self.out_file = out_file        
 
 
116
        print >> out_file, 'events: Ticks'
 
 
117
        self._print_summary()
 
 
118
        for entry in self.data:
 
 
121
    def _print_summary(self):
 
 
123
        for entry in self.data:
 
 
124
            totaltime = int(entry.totaltime * 1000)
 
 
125
            max_cost = max(max_cost, totaltime)
 
 
126
        print >> self.out_file, 'summary: %d' % (max_cost,)
 
 
128
    def _entry(self, entry):
 
 
129
        out_file = self.out_file
 
 
131
        inlinetime = int(entry.inlinetime * 1000)
 
 
132
        #print >> out_file, 'ob=%s' % (code.co_filename,)
 
 
133
        print >> out_file, 'fi=%s' % (code.co_filename,)
 
 
134
        print >> out_file, 'fn=%s' % (label(code, True),)
 
 
135
        print >> out_file, '%d %d' % (code.co_firstlineno, inlinetime)
 
 
136
        # recursive calls are counted in entry.calls
 
 
141
        for subentry in calls:
 
 
142
            self._subentry(code.co_firstlineno, subentry)
 
 
145
    def _subentry(self, lineno, subentry):
 
 
146
        out_file = self.out_file
 
 
148
        totaltime = int(subentry.totaltime * 1000)
 
 
149
        #print >> out_file, 'cob=%s' % (code.co_filename,)
 
 
150
        print >> out_file, 'cfn=%s' % (label(code, True),)
 
 
151
        print >> out_file, 'cfi=%s' % (code.co_filename,)
 
 
152
        print >> out_file, 'calls=%d %d' % (
 
 
153
            subentry.callcount, code.co_firstlineno)
 
 
154
        print >> out_file, '%d %d' % (lineno, totaltime)
 
 
159
def label(code, calltree=False):
 
 
160
    if isinstance(code, str):
 
 
163
        mname = _fn2mod[code.co_filename]
 
 
165
        for k, v in sys.modules.iteritems():
 
 
168
            if not hasattr(v, '__file__'):
 
 
170
            if not isinstance(v.__file__, str):
 
 
172
            if v.__file__.startswith(code.co_filename):
 
 
173
                mname = _fn2mod[code.co_filename] = k
 
 
176
            mname = _fn2mod[code.co_filename] = '<%s>'%code.co_filename
 
 
178
        return '%s %s:%d' % (code.co_name, mname, code.co_firstlineno)
 
 
180
        return '%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name)
 
 
183
if __name__ == '__main__':
 
 
185
    sys.argv = sys.argv[1:]
 
 
187
        print >> sys.stderr, "usage: lsprof.py <script> <arguments...>"
 
 
189
    sys.path.insert(0, os.path.abspath(os.path.dirname(sys.argv[0])))
 
 
190
    stats = profile(execfile, sys.argv[0], globals(), locals())