__init__.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """High-perfomance logging profiler, mostly written in C."""
  2. import _hotshot
  3. from _hotshot import ProfilerError
  4. class Profile:
  5. def __init__(self, logfn, lineevents=0, linetimings=1):
  6. self.lineevents = lineevents and 1 or 0
  7. self.linetimings = (linetimings and lineevents) and 1 or 0
  8. self._prof = p = _hotshot.profiler(
  9. logfn, self.lineevents, self.linetimings)
  10. # Attempt to avoid confusing results caused by the presence of
  11. # Python wrappers around these functions, but only if we can
  12. # be sure the methods have not been overridden or extended.
  13. if self.__class__ is Profile:
  14. self.close = p.close
  15. self.start = p.start
  16. self.stop = p.stop
  17. self.addinfo = p.addinfo
  18. def close(self):
  19. """Close the logfile and terminate the profiler."""
  20. self._prof.close()
  21. def fileno(self):
  22. """Return the file descriptor of the profiler's log file."""
  23. return self._prof.fileno()
  24. def start(self):
  25. """Start the profiler."""
  26. self._prof.start()
  27. def stop(self):
  28. """Stop the profiler."""
  29. self._prof.stop()
  30. def addinfo(self, key, value):
  31. """Add an arbitrary labelled value to the profile log."""
  32. self._prof.addinfo(key, value)
  33. # These methods offer the same interface as the profile.Profile class,
  34. # but delegate most of the work to the C implementation underneath.
  35. def run(self, cmd):
  36. """Profile an exec-compatible string in the script
  37. environment.
  38. The globals from the __main__ module are used as both the
  39. globals and locals for the script.
  40. """
  41. import __main__
  42. dict = __main__.__dict__
  43. return self.runctx(cmd, dict, dict)
  44. def runctx(self, cmd, globals, locals):
  45. """Evaluate an exec-compatible string in a specific
  46. environment.
  47. The string is compiled before profiling begins.
  48. """
  49. code = compile(cmd, "<string>", "exec")
  50. self._prof.runcode(code, globals, locals)
  51. return self
  52. def runcall(self, func, *args, **kw):
  53. """Profile a single call of a callable.
  54. Additional positional and keyword arguments may be passed
  55. along; the result of the call is returned, and exceptions are
  56. allowed to propogate cleanly, while ensuring that profiling is
  57. disabled on the way out.
  58. """
  59. return self._prof.runcall(func, args, kw)