/apiary/tools/lsprof.py

https://bitbucket.org/lindenlab/apiary/ · Python · 120 lines · 97 code · 15 blank · 8 comment · 34 complexity · 89c3a00a016f46c77a004b9154939929 MD5 · raw file

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