[Python-Dev] profiler decorator - is it worth for inclusion? (original) (raw)

Giampaolo Rodolà g.rodola at gmail.com
Sat Jul 17 16:03:36 CEST 2010


Provided a patch on the tracker: http://bugs.python.org/issue9285

Further comments can be submitted there, if any.

--- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil

2010/7/15 Giampaolo Rodolà <g.rodola at gmail.com>:

2010/7/15 Brian Curtin <brian.curtin at gmail.com>:

On Thu, Jul 15, 2010 at 13:45, Giampaolo Rodolà <g.rodola at gmail.com> wrote:

Today I was looking for a quick and dirty way to profile a method of a class. I was thinking that cProfile module had a decorator for this but I was wrong so I decided to write one based on hotshot. Would it be worth for inclusion? Since hotshot is gone in 3.x, I'd guess the chances are probably slim.


Python-Dev mailing list Python-Dev at python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/g.rodola%40gmail.com

Here's one using cProfile instead. I was using hotshot because I wasn't aware of cProfile.Profile.runcall which is currently not documented (I'm going to file a bug report). def profile(sort='cumulative', lines=30, stripdirs=True):  """A decorator which profiles a callable.  Example usage:  >>> @profile()  ... def factorial(n):  ...     n = abs(int(n))  ...     if n < 1:_  _...             n = 1_  _...     x = 1_  _...     for i in range(1, n+1):_  _...             x = i * x_  _...     return x_  _..._  _>>> factorial(5)  Thu Jul 15 20:58:21 2010    /tmp/tmpIDejr5 4 function calls in 0.000 CPU seconds Ordered by: internal time, call count ncalls  tottime  percall  cumtime  percall filename:lineno(function)  1    0.000    0.000    0.000    0.000 profiler.py:120(factorial)  1    0.000    0.000    0.000    0.000 {range}  1    0.000    0.000    0.000    0.000 {abs}  1    0.000    0.000    0.000    0.000 {method 'disable' of 'lsprof.Profiler' objects}  120  """  def outer(fun):  def inner(*args, **kwargs):  file = tempfile.NamedTemporaryFile()  prof = cProfile.Profile()  try:  ret = prof.runcall(fun, *args, **kwargs)  except:  file.close()  raise  prof.dumpstats(file.name)  stats = pstats.Stats(file.name)  if stripdirs:  stats.stripdirs()  if isinstance(sort, tuple):  stats.sortstats(*sort)  else:  stats.sortstats(sort)  stats.printstats(lines)  file.close()  return ret  return inner  return outer --- Giampaolo http://code.google.com/p/pyftpdlib http://code.google.com/p/psutil



More information about the Python-Dev mailing list