Source code for irfpy.util.profile

''' A simple decorator for profiling.

.. codeauthor:: Yoshifumi Futaana

This is based on the implementation of Expert Python Programming
by Tarek Ziade.  Code referred from p.330 in Japanese translation.

How to profile a function

.. code-block:: python

    import time
    def med():
        time.sleep(0.01)

    def lgt():
        time.sleep(0.001)

    def hvy():
        print 'heavy process...'
        for i in range(100):
            lgt()
            med()
            med()
        time.sleep(0.5)

    @profile('A test for main', list=6)
    def main():
            for i in range(2):
                hvy()

    print 'Using as a decorator'
    main()

    print 'Using as a normal function'
    p = profile()(med)
    p()

See sample/snippet/profile_sample.py

'''

import tempfile
import os
import cProfile
import pstats


[docs]def profile(name='profile', column='time', list=5): def _profile(function): def __profile(*args, **kw): s = tempfile.mktemp() profiler = cProfile.Profile() try: return profiler.runcall(function, *args, **kw) finally: print('=' * 80) print('profile:', name) print('=' * 80) profiler.dump_stats(s) p = pstats.Stats(s) p.sort_stats(column).print_stats(list) return __profile return _profile
import unittest import doctest
[docs]def doctests(): return unittest.TestSuite(( doctest.DocTestSuite(), ))
if __name__ == '__main__': unittest.main(defaultTest='doctests')