lsprof.py 3.8 KB

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