PageRenderTime 51ms CodeModel.GetById 38ms app.highlight 7ms RepoModel.GetById 3ms app.codeStats 0ms

/apiary/tools/lsprof.py

https://bitbucket.org/lindenlab/apiary/
Python | 120 lines | 97 code | 15 blank | 8 comment | 44 complexity | 89c3a00a016f46c77a004b9154939929 MD5 | raw file
  1# taken from http://codespeak.net/svn/user/arigo/hack/misc/lsprof/lsprof.py
  2
  3import sys
  4try:
  5    from _lsprof import Profiler, profiler_entry
  6except ImportError, e:
  7    print "Error when trying to import from _lsprof: %s" % e
  8    print "Make sure lsprof (http://codespeak.net/svn/user/arigo/hack/misc/lsprof/) is installed."
  9    sys.exit(1)
 10
 11__all__ = ['profile', 'Stats']
 12
 13def profile(f, *args, **kwds):
 14    """XXX docstring"""
 15    p = Profiler()
 16    p.enable(subcalls=True, builtins=True)
 17    try:
 18        f(*args, **kwds)
 19    finally:
 20        p.disable()
 21    return Stats(p.getstats())
 22
 23
 24class Stats(object):
 25    """XXX docstring"""
 26
 27    def __init__(self, data):
 28        self.data = data
 29
 30    def sort(self, crit="inlinetime"):
 31        """XXX docstring"""
 32        if crit not in profiler_entry.__dict__:
 33            raise ValueError("Can't sort by %s" % crit)
 34        self.data.sort(lambda b, a: cmp(getattr(a, crit),
 35                                        getattr(b, crit)))
 36        for e in self.data:
 37            if e.calls:
 38                e.calls.sort(lambda b, a: cmp(getattr(a, crit),
 39                                              getattr(b, crit)))
 40
 41    def pprint(self, top=None, file=None, limit=None, climit=None):
 42        """XXX docstring"""
 43        if file is None:
 44            file = sys.stdout
 45        d = self.data
 46        if top is not None:
 47            d = d[:top]
 48        cols = "% 12s %12s %11.4f %11.4f   %s\n"
 49        hcols = "% 12s %12s %12s %12s %s\n"
 50        file.write(hcols % ("CallCount", "Recursive", "Total(ms)",
 51                            "Inline(ms)", "module:lineno(function)"))
 52        count = 0
 53        for e in d:
 54            file.write(cols % (e.callcount, e.reccallcount, e.totaltime,
 55                               e.inlinetime, label(e.code)))
 56            count += 1
 57            if limit is not None and count == limit:
 58                return
 59            ccount = 0
 60            if e.calls:
 61                for se in e.calls:
 62                    file.write(cols % ("+%s" % se.callcount, se.reccallcount,
 63                                       se.totaltime, se.inlinetime,
 64                                       "+%s" % label(se.code)))
 65                    count += 1
 66                    ccount += 1
 67                    if limit is not None and count == limit:
 68                        return
 69                    if climit is not None and ccount == climit:
 70                        break
 71
 72    def freeze(self):
 73        """Replace all references to code objects with string
 74        descriptions; this makes it possible to pickle the instance."""
 75
 76        # this code is probably rather ickier than it needs to be!
 77        for i in range(len(self.data)):
 78            e = self.data[i]
 79            if not isinstance(e.code, str):
 80                self.data[i] = type(e)((label(e.code),) + e[1:])
 81            if e.calls:
 82                for j in range(len(e.calls)):
 83                    se = e.calls[j]
 84                    if not isinstance(se.code, str):
 85                        e.calls[j] = type(se)((label(se.code),) + se[1:])
 86
 87_fn2mod = {}
 88
 89def label(code):
 90    if isinstance(code, str):
 91        return code
 92    try:
 93        mname = _fn2mod[code.co_filename]
 94    except KeyError:
 95        for k, v in sys.modules.iteritems():
 96            if v is None:
 97                continue
 98            if not hasattr(v, '__file__'):
 99                continue
100            if not isinstance(v.__file__, str):
101                continue
102            if v.__file__.startswith(code.co_filename):
103                mname = _fn2mod[code.co_filename] = k
104                break
105        else:
106            mname = _fn2mod[code.co_filename] = '<%s>'%code.co_filename
107
108    return '%s:%d(%s)' % (mname, code.co_firstlineno, code.co_name)
109
110
111if __name__ == '__main__':
112    import os
113    sys.argv = sys.argv[1:]
114    if not sys.argv:
115        print >> sys.stderr, "usage: lsprof.py <script> <arguments...>"
116        sys.exit(2)
117    sys.path.insert(0, os.path.abspath(os.path.dirname(sys.argv[0])))
118    stats = profile(execfile, sys.argv[0], globals(), locals())
119    stats.sort()
120    stats.pprint()