Long ago I posted a patch for this (decorator + context manager) but I bumped into a weird error I wasn't able to fix (see last comment):
http://bugs.python.org/issue9285

On Wed, Nov 2, 2016 at 10:45 PM, Tim Mitchell <tim.mitchell@leapfrog3d.com> wrote:
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@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@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.

_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/



--
Giampaolo - http://grodola.blogspot.com