def profile(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 ... """ def outer(fun): import cProfile import tempfile import os try: PROFILE_LOG_BASE = '/tmp' except: PROFILE_LOG_BASE = tempfile.gettempdir() def inner(*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() raise prof.dump_stats(file_name) file.close() return ret return inner # in case this is defined as "@profile" instead of "@profile()" if hasattr(sort, '__call__'): fun = sort sort = 'cumulative' outer = outer(fun) return outer