Python profiling decorator
By Maxime Biais, Saturday 20 January 2007 at 18:27 :: Python :: #18 :: rss
I often profile or time my functions using hotshot profiler and timeit modules from the stantard library. Recently, I wrote this simple profiler decorator:
import hotshot, hotshot.stats def profileit(printlines=1): def _my(func): def _func(*args, **kargs): prof = hotshot.Profile("profiling.data") res = prof.runcall(func, *args, **kargs) prof.close() stats = hotshot.stats.load("profiling.data") stats.strip_dirs() stats.sort_stats('time', 'calls') print ">>>---- Begin profiling print" stats.print_stats(printlines) print ">>>---- End profiling print" return res return _func return _my
Usage:
def mip(): a = 0 for i in range(10000): a += 1 return a @profileit(20) def mop(): a = 0 for i in range(100): a += mip() return a print mop()
Results:
>>>---- Begin profiling print
101 function calls in 0.580 CPU seconds
Ordered by: internal time, call count
ncalls tottime percall cumtime percall filename:lineno(function)
100 0.578 0.006 0.578 0.006 mip.py:29(mip)
1 0.002 0.002 0.580 0.580 mip.py:35(mop)
0 0.000 0.000 profile:0(profiler)
>>>---- End profiling print
1000000
Now the same code with printlines=1 settings (@profileit(1)):
>>>---- Begin profiling print
101 function calls in 0.587 CPU seconds
Ordered by: internal time, call count
List reduced from 3 to 1 due to restriction <1>
ncalls tottime percall cumtime percall filename:lineno(function)
100 0.585 0.006 0.585 0.006 mip.py:29(mip)
>>>---- End profiling print
1000000




Comments
No comment.
Write your comment