~bzr-pqm/bzr/bzr.dev

1185.33.86 by Martin Pool
Add additional module for lsprof.
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
5
2493.2.3 by Ian Clatworthy
changes requested in jameinel's review incorporated
6
import cPickle
7
import os
1185.33.86 by Martin Pool
Add additional module for lsprof.
8
import sys
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
9
import thread
10
import threading
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
11
from _lsprof import Profiler, profiler_entry
1185.33.86 by Martin Pool
Add additional module for lsprof.
12
2805.7.4 by Ian Clatworthy
incorporate feedback from lifeless
13
1185.33.86 by Martin Pool
Add additional module for lsprof.
14
__all__ = ['profile', 'Stats']
15
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
16
_g_threadmap = {}
17
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
18
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
19
def _thread_profile(f, *args, **kwds):
20
    # we lose the first profile point for a new thread in order to trampoline
21
    # a new Profile object into place
22
    global _g_threadmap
23
    thr = thread.get_ident()
24
    _g_threadmap[thr] = p = Profiler()
25
    # this overrides our sys.setprofile hook:
1706.2.7 by Robey Pointer
pull over some changes from the original lsprof
26
    p.enable(subcalls=True, builtins=True)
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
27
28
1185.33.86 by Martin Pool
Add additional module for lsprof.
29
def profile(f, *args, **kwds):
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
30
    """Run a function profile.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
31
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
32
    Exceptions are not caught: If you need stats even when exceptions are to be
33
    raised, passing in a closure that will catch the exceptions and transform
34
    them appropriately for your driver function.
35
3696.3.5 by Robert Collins
Streamline _walkdirs_utf8 for utf8 file systems, reducing time to traverse a mozilla tree from 1s to .6 seconds. (Robert Collins)
36
    :return: The functions return value and a stats object.
37
    """
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
38
    global _g_threadmap
1185.33.86 by Martin Pool
Add additional module for lsprof.
39
    p = Profiler()
40
    p.enable(subcalls=True)
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
41
    threading.setprofile(_thread_profile)
1185.33.86 by Martin Pool
Add additional module for lsprof.
42
    try:
4084.6.1 by Robert Collins
Refactor profiling exception handling to restore clear layers - command handling in commands.py, profiling in lsprof.py.
43
        ret = f(*args, **kwds)
1185.33.86 by Martin Pool
Add additional module for lsprof.
44
    finally:
45
        p.disable()
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
46
        for pp in _g_threadmap.values():
47
            pp.disable()
48
        threading.setprofile(None)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
49
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
50
    threads = {}
51
    for tid, pp in _g_threadmap.items():
52
        threads[tid] = Stats(pp.getstats(), {})
53
    _g_threadmap = {}
54
    return ret, Stats(p.getstats(), threads)
1185.33.86 by Martin Pool
Add additional module for lsprof.
55
56
57
class Stats(object):
58
    """XXX docstring"""
59
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
60
    def __init__(self, data, threads):
1185.33.86 by Martin Pool
Add additional module for lsprof.
61
        self.data = data
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
62
        self.threads = threads
1185.33.86 by Martin Pool
Add additional module for lsprof.
63
64
    def sort(self, crit="inlinetime"):
65
        """XXX docstring"""
66
        if crit not in profiler_entry.__dict__:
67
            raise ValueError, "Can't sort by %s" % crit
68
        self.data.sort(lambda b, a: cmp(getattr(a, crit),
69
                                        getattr(b, crit)))
70
        for e in self.data:
71
            if e.calls:
72
                e.calls.sort(lambda b, a: cmp(getattr(a, crit),
73
                                              getattr(b, crit)))
74
75
    def pprint(self, top=None, file=None):
76
        """XXX docstring"""
77
        if file is None:
78
            file = sys.stdout
79
        d = self.data
80
        if top is not None:
81
            d = d[:top]
82
        cols = "% 12s %12s %11.4f %11.4f   %s\n"
83
        hcols = "% 12s %12s %12s %12s %s\n"
84
        cols2 = "+%12s %12s %11.4f %11.4f +  %s\n"
85
        file.write(hcols % ("CallCount", "Recursive", "Total(ms)",
86
                            "Inline(ms)", "module:lineno(function)"))
87
        for e in d:
88
            file.write(cols % (e.callcount, e.reccallcount, e.totaltime,
89
                               e.inlinetime, label(e.code)))
90
            if e.calls:
91
                for se in e.calls:
92
                    file.write(cols % ("+%s" % se.callcount, se.reccallcount,
93
                                       se.totaltime, se.inlinetime,
94
                                       "+%s" % label(se.code)))
95
96
    def freeze(self):
97
        """Replace all references to code objects with string
98
        descriptions; this makes it possible to pickle the instance."""
99
100
        # this code is probably rather ickier than it needs to be!
101
        for i in range(len(self.data)):
102
            e = self.data[i]
103
            if not isinstance(e.code, str):
104
                self.data[i] = type(e)((label(e.code),) + e[1:])
1706.2.7 by Robey Pointer
pull over some changes from the original lsprof
105
            if e.calls:
106
                for j in range(len(e.calls)):
107
                    se = e.calls[j]
108
                    if not isinstance(se.code, str):
109
                        e.calls[j] = type(se)((label(se.code),) + se[1:])
1553.7.2 by Robey Pointer
add threading support -- each thread created during an lsprof session gets its own profile object, and the Stats objects are attached to a 'threads' member of the final Stats object
110
        for s in self.threads.values():
111
            s.freeze()
112
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
113
    def calltree(self, file):
114
        """Output profiling data in calltree format (for KCacheGrind)."""
115
        _CallTreeFilter(self.data).output(file)
116
2493.2.3 by Ian Clatworthy
changes requested in jameinel's review incorporated
117
    def save(self, filename, format=None):
118
        """Save profiling data to a file.
119
120
        :param filename: the name of the output file
121
        :param format: 'txt' for a text representation;
122
            'callgrind' for calltree format;
123
            otherwise a pickled Python object. A format of None indicates
2654.2.2 by Ian Clatworthy
Put all format detection stuff in one spot as requested by John Arbash Meinel
124
            that the format to use is to be found from the filename. If
125
            the name starts with callgrind.out, callgrind format is used
126
            otherwise the format is given by the filename extension.
2493.2.3 by Ian Clatworthy
changes requested in jameinel's review incorporated
127
        """
128
        if format is None:
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
129
            basename = os.path.basename(filename)
2805.7.2 by Ian Clatworthy
use basename, not full path, when checking for callgrind.out file prefix
130
            if basename.startswith('callgrind.out'):
2654.2.2 by Ian Clatworthy
Put all format detection stuff in one spot as requested by John Arbash Meinel
131
                format = "callgrind"
132
            else:
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
133
                ext = os.path.splitext(filename)[1]
2654.2.2 by Ian Clatworthy
Put all format detection stuff in one spot as requested by John Arbash Meinel
134
                if len(ext) > 1:
135
                    format = ext[1:]
2493.2.3 by Ian Clatworthy
changes requested in jameinel's review incorporated
136
        outfile = open(filename, 'wb')
137
        try:
138
            if format == "callgrind":
139
                self.calltree(outfile)
140
            elif format == "txt":
141
                self.pprint(file=outfile)
142
            else:
143
                self.freeze()
144
                cPickle.dump(self, outfile, 2)
145
        finally:
146
            outfile.close()
147
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
148
149
class _CallTreeFilter(object):
2493.2.2 by Ian Clatworthy
Incorporate feedback from Robert Collins
150
    """Converter of a Stats object to input suitable for KCacheGrind.
151
152
    This code is taken from http://ddaa.net/blog/python/lsprof-calltree
153
    with the changes made by J.P. Calderone and Itamar applied. Note that
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
154
    isinstance(code, str) needs to be used at times to determine if the code
2493.2.2 by Ian Clatworthy
Incorporate feedback from Robert Collins
155
    object is actually an external code object (with a filename, etc.) or
156
    a Python built-in.
157
    """
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
158
159
    def __init__(self, data):
160
        self.data = data
161
        self.out_file = None
162
163
    def output(self, out_file):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
164
        self.out_file = out_file
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
165
        out_file.write('events: Ticks\n')
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
166
        self._print_summary()
167
        for entry in self.data:
168
            self._entry(entry)
169
170
    def _print_summary(self):
171
        max_cost = 0
172
        for entry in self.data:
173
            totaltime = int(entry.totaltime * 1000)
174
            max_cost = max(max_cost, totaltime)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
175
        self.out_file.write('summary: %d\n' % (max_cost,))
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
176
177
    def _entry(self, entry):
178
        out_file = self.out_file
179
        code = entry.code
180
        inlinetime = int(entry.inlinetime * 1000)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
181
        #out_file.write('ob=%s\n' % (code.co_filename,))
182
        if isinstance(code, str):
183
            out_file.write('fi=~\n')
184
        else:
185
            out_file.write('fi=%s\n' % (code.co_filename,))
186
        out_file.write('fn=%s\n' % (label(code, True),))
187
        if isinstance(code, str):
2911.6.4 by Blake Winton
Fix test failures
188
            out_file.write('0  %s\n' % (inlinetime,))
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
189
        else:
190
            out_file.write('%d %d\n' % (code.co_firstlineno, inlinetime))
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
191
        # recursive calls are counted in entry.calls
192
        if entry.calls:
193
            calls = entry.calls
194
        else:
195
            calls = []
2493.2.1 by Ian Clatworthy
make profiling information easier to view and better documented
196
        if isinstance(code, str):
197
            lineno = 0
198
        else:
199
            lineno = code.co_firstlineno
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
200
        for subentry in calls:
2493.2.1 by Ian Clatworthy
make profiling information easier to view and better documented
201
            self._subentry(lineno, subentry)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
202
        out_file.write('\n')
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
203
204
    def _subentry(self, lineno, subentry):
205
        out_file = self.out_file
206
        code = subentry.code
207
        totaltime = int(subentry.totaltime * 1000)
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
208
        #out_file.write('cob=%s\n' % (code.co_filename,))
209
        out_file.write('cfn=%s\n' % (label(code, True),))
2493.2.1 by Ian Clatworthy
make profiling information easier to view and better documented
210
        if isinstance(code, str):
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
211
            out_file.write('cfi=~\n')
212
            out_file.write('calls=%d 0\n' % (subentry.callcount,))
2493.2.1 by Ian Clatworthy
make profiling information easier to view and better documented
213
        else:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
214
            out_file.write('cfi=%s\n' % (code.co_filename,))
215
            out_file.write('calls=%d %d\n' % (
216
                subentry.callcount, code.co_firstlineno))
217
        out_file.write('%d %d\n' % (lineno, totaltime))
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
218
1185.33.86 by Martin Pool
Add additional module for lsprof.
219
_fn2mod = {}
220
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
221
def label(code, calltree=False):
1185.33.86 by Martin Pool
Add additional module for lsprof.
222
    if isinstance(code, str):
223
        return code
224
    try:
225
        mname = _fn2mod[code.co_filename]
226
    except KeyError:
1711.2.124 by John Arbash Meinel
Use sys.modules.items() to prevent running into site.py problems
227
        for k, v in sys.modules.items():
1185.33.86 by Martin Pool
Add additional module for lsprof.
228
            if v is None:
229
                continue
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
230
            if getattr(v, '__file__', None) is None:
1185.33.86 by Martin Pool
Add additional module for lsprof.
231
                continue
232
            if not isinstance(v.__file__, str):
233
                continue
234
            if v.__file__.startswith(code.co_filename):
235
                mname = _fn2mod[code.co_filename] = k
236
                break
237
        else:
238
            mname = _fn2mod[code.co_filename] = '<%s>'%code.co_filename
1553.7.3 by Robey Pointer
patch from ddaa to add kcachegrind output-format support to lsprof
239
    if calltree:
240
        return '%s %s:%d' % (code.co_name, mname, code.co_firstlineno)
241
    else:
242
        return '%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name)
1185.33.86 by Martin Pool
Add additional module for lsprof.
243
244
245
if __name__ == '__main__':
246
    import os
247
    sys.argv = sys.argv[1:]
248
    if not sys.argv:
2911.6.1 by Blake Winton
Change 'print >> f,'s to 'f.write('s.
249
        sys.stderr.write("usage: lsprof.py <script> <arguments...>\n")
1185.33.86 by Martin Pool
Add additional module for lsprof.
250
        sys.exit(2)
251
    sys.path.insert(0, os.path.abspath(os.path.dirname(sys.argv[0])))
252
    stats = profile(execfile, sys.argv[0], globals(), locals())
253
    stats.sort()
254
    stats.pprint()