[Python-Dev] profiler decorator - is it worth for inclusion?
Giampaolo Rodolà
g.rodola at gmail.com
Thu Jul 15 21:24:39 CEST 2010
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, strip_dirs=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.dump_stats(file.name)
stats = pstats.Stats(file.name)
if strip_dirs:
stats.strip_dirs()
if isinstance(sort, tuple):
stats.sort_stats(*sort)
else:
stats.sort_stats(sort)
stats.print_stats(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