Python cProfile

From wikinotes

cProfile allows you to test speed function-by-function to find out how long each takes to run so you can determine which to speed up.


cProfiler and profiler are essentially identical. profiler is a pure python implementation, that should be easier to extend. pstats organizes and filters both profiler and cProfiler's information.

I haven't found using the profiler inside the script to be too helpful yet, (although you can watch only certain functions). using it directly from the commandline takes the least amount of effort, and is probably the most useful.

python2 -m cProfile -s <sort-order(tottime, cumulative, ncalls,...)> myscript.py
def test( varA=None ):
	print varA

if __name__ == '__main__':
	import cProfile
	import pstats

	## Running profiler
	##
	profiler = cProfile.Profile()

	profiler.enable()																## Run profiler for arbitrary time
	profiler.disable()

	varA = 'abc'
	cProfile.runctx( 'testprint( varA )', globals(), locals() )		## Run func with profiler (using current environment)



	## Doing things with profiler information
	##
	profiler.dump_stats( '/path/to/file' )									## Dump to file

	stats = pstats.Stats( profiler )											## print/filter stats
	stats.print_stats( '*match_module_name' )