defprofile(log_file,sort='cumulative',strip_dirs=False):"""A decorator which profiles a callable, or a view function, etc. Example usage: >>> @profile('/tmp/file_name') 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 ... """defouter(fun):importcProfileimporttempfileimportostry:PROFILE_LOG_BASE='/tmp'except:PROFILE_LOG_BASE=tempfile.gettempdir()definner(*args,**kwargs):file_name=os.path.join(PROFILE_LOG_BASE,log_file)file=open(file_name,"w")prof=cProfile.Profile()try:ret=prof.runcall(fun,*args,**kwargs)except:file.close()raiseprof.dump_stats(file_name)file.close()returnretreturninner# in case this is defined as "@profile" instead of "@profile()"ifhasattr(sort,'__call__'):fun=sortsort='cumulative'outer=outer(fun)returnouter
Comments
Please login first before commenting.