/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/lsprof.py

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
5
5
 
6
6
from __future__ import absolute_import
7
7
 
8
 
import codecs
9
 
try:
10
 
    import cPickle as pickle
11
 
except ImportError:
12
 
    import pickle
13
 
import operator
 
8
import cPickle
14
9
import os
15
10
import sys
16
 
try:
17
 
    import _thread
18
 
except ImportError:
19
 
    import thread as _thread
 
11
import thread
20
12
import threading
21
13
from _lsprof import Profiler, profiler_entry
22
14
 
23
 
from . import errors
 
15
from bzrlib import errors
24
16
 
25
17
__all__ = ['profile', 'Stats']
26
18
 
60
52
    This is needed because profiling involves global manipulation of the python
61
53
    interpreter state. As such you cannot perform multiple profiles at once.
62
54
    Trying to do so will lock out the second profiler unless the global 
63
 
    breezy.lsprof.BzrProfiler.profiler_block is set to 0. Setting it to 0 will
 
55
    bzrlib.lsprof.BzrProfiler.profiler_block is set to 0. Setting it to 0 will
64
56
    cause profiling to fail rather than blocking.
65
57
    """
66
58
 
95
87
        This unhooks from threading and cleans up the profiler, returning
96
88
        the gathered Stats object.
97
89
 
98
 
        :return: A breezy.lsprof.Stats object.
 
90
        :return: A bzrlib.lsprof.Stats object.
99
91
        """
100
92
        try:
101
93
            self.p.disable()
115
107
    def _thread_profile(self, f, *args, **kwds):
116
108
        # we lose the first profile point for a new thread in order to
117
109
        # trampoline a new Profile object into place
118
 
        thr = _thread.get_ident()
 
110
        thr = thread.get_ident()
119
111
        self._g_threadmap[thr] = p = Profiler()
120
112
        # this overrides our sys.setprofile hook:
121
113
        p.enable(subcalls=True, builtins=True)
133
125
        self.data = data
134
126
        self.threads = threads
135
127
 
136
 
    def sort(self, crit="inlinetime", reverse=True):
 
128
    def sort(self, crit="inlinetime"):
137
129
        """Sort the data by the supplied critera.
138
130
 
139
131
        :param crit: the data attribute used as the sort key."""
140
 
        if crit not in profiler_entry.__dict__ or crit == 'code':
141
 
            raise ValueError("Can't sort by %s" % crit)
142
 
 
143
 
        key_func = operator.attrgetter(crit)
144
 
        self.data.sort(key=key_func, reverse=reverse)
145
 
 
 
132
        if crit not in profiler_entry.__dict__:
 
133
            raise ValueError, "Can't sort by %s" % crit
 
134
        self.data.sort(lambda b, a: cmp(getattr(a, crit),
 
135
                                        getattr(b, crit)))
146
136
        for e in self.data:
147
137
            if e.calls:
148
 
                e.calls.sort(key=key_func, reverse=reverse)
 
138
                e.calls.sort(lambda b, a: cmp(getattr(a, crit),
 
139
                                              getattr(b, crit)))
149
140
 
150
141
    def pprint(self, top=None, file=None):
151
142
        """Pretty-print the data as plain text for human consumption.
213
204
                ext = os.path.splitext(filename)[1]
214
205
                if len(ext) > 1:
215
206
                    format = ext[1:]
216
 
        with open(filename, 'wb') as outfile:
 
207
        outfile = open(filename, 'wb')
 
208
        try:
217
209
            if format == "callgrind":
218
 
                # The callgrind format states it is 'ASCII based':
219
 
                # <http://valgrind.org/docs/manual/cl-format.html>
220
 
                # But includes filenames so lets ignore and use UTF-8.
221
 
                self.calltree(codecs.getwriter('utf-8')(outfile))
 
210
                self.calltree(outfile)
222
211
            elif format == "txt":
223
 
                self.pprint(file=codecs.getwriter('utf-8')(outfile))
 
212
                self.pprint(file=outfile)
224
213
            else:
225
214
                self.freeze()
226
 
                pickle.dump(self, outfile, 2)
 
215
                cPickle.dump(self, outfile, 2)
 
216
        finally:
 
217
            outfile.close()
227
218
 
228
219
 
229
220
class _CallTreeFilter(object):
323
314
        return '%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name)
324
315
 
325
316
 
326
 
def main():
 
317
if __name__ == '__main__':
 
318
    import os
327
319
    sys.argv = sys.argv[1:]
328
320
    if not sys.argv:
329
321
        sys.stderr.write("usage: lsprof.py <script> <arguments...>\n")
330
322
        sys.exit(2)
331
 
    import runpy
332
 
    result, stats = profile(runpy.run_path, sys.argv[0], run_name='__main__')
 
323
    sys.path.insert(0, os.path.abspath(os.path.dirname(sys.argv[0])))
 
324
    stats = profile(execfile, sys.argv[0], globals(), locals())
333
325
    stats.sort()
334
326
    stats.pprint()
335
 
 
336
 
 
337
 
if __name__ == '__main__':
338
 
    main()