[Python-Dev] profiler decorator - is it worth for inclusion?

Giampaolo Rodolà g.rodola at gmail.com
Thu Jul 15 20:45:53 CEST 2010


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?


#!/usr/bin/env python

import hotshot
import hotshot.stats
import tempfile
import pstats


def profile(sort='cumulative', lines=30, strip_dirs=False):
    """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)
             1 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:60(factorial)
            0    0.000             0.000          profile:0(profiler)


    120
    >>>
    """
    def outer(fun):
        def inner(*args, **kwargs):
            file = tempfile.NamedTemporaryFile()
            prof = hotshot.Profile(file.name)
            try:
                ret = prof.runcall(fun, *args, **kwargs)
            finally:
                prof.close()

            stats = hotshot.stats.load(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)

            return ret
        return inner

    return outer


More information about the Python-Dev mailing list