[Python-ideas] Small improvements to the profile/cProfile API
Tim Mitchell
tim.mitchell at leapfrog3d.com
Wed Nov 2 17:45:40 EDT 2016
Hi Ben,
Mostly I just print to stdout, I imagine more flexibility would be needed
in general.
This is for python 2.7 - don't know if it works for 3.
def profile(sort='time', restriction=(), callers=None, callees=None,
filename=None):
def _profileDecorator(func):
"print profile stats for decorated function"
def wrapper(*args, **kwargs):
print 'Profile for:', func.__name__
prof = cProfile.Profile()
result = prof.runcall(func, *args, **kwargs)
_, statsFileName = tempfile.mkstemp()
prof.dump_stats(statsFileName)
if filename is None:
stats = pstats.Stats(statsFileName)
else:
stats = pstats.Stats(statsFileName, stream=open(filename, 'w'))
if isinstance(sort, basestring):
stats.sort_stats(sort)
else:
stats.sort_stats(*sort)
if isinstance(restriction, (tuple, list)):
stats.print_stats(*restriction)
else:
stats.print_stats(restriction)
if callers is not None:
if isinstance(callers, basestring):
stats.print_callers(callers)
else:
stats.print_callers(*callers)
if callees is not None:
if isinstance(callees, basestring):
stats.print_callees(callees)
else:
stats.print_callees(*callees)
return result
return wrapper
return _profileDecorator
Cheers
Tim
On 3 November 2016 at 09:58, Ben Hoyt <benhoyt at gmail.com> wrote:
> Okay, got it, that sounds fair enough. With your @profile decorator how do
> you tell it when and where to print the output? Can you post the source for
> your decorator?
>
> On Wed, Nov 2, 2016 at 4:52 PM, Tim Mitchell <tim.mitchell at leapfrog3d.com>
> wrote:
>
>> I use an @profile() decorator for almost all my profiling. If you want
>> to profile function foo you just decorate it and re-run the program.
>> With a with block you have to find the places where foo is called and put
>> with statements around the calls.
>> I think both approaches are equally valid and useful.
>>
>>> conduct/ <http://python.org/psf/codeofconduct/>
>>>
>>
>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161103/92571e37/attachment.html>
More information about the Python-ideas
mailing list