Quickly profile your Python code

- 1 min

Quickly profile your Python code

Profiling using a decorator:

Given some Python function for which profiling is required, add this decorator definition to the script:

def profile(profiled_func):
    
    def wrap(*args, **kwargs):
        import cProfile
        pr = cProfile.Profile()
        pr.enable()

        result = profiled_func(*args, **kwargs)

        pr.disable()
        pr.print_stats(sort='time')
        return result
    
    return wrap

Then, upon the definition of the function one wants to profile, just decorate it:

@profile
def some_fun():
	pass

Upon running the script, the output will include the following:

comments powered by Disqus
rss facebook twitter github gitlab youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora